Ryan Turner
Ryan Turner

Reputation: 99

javascript toString() does weird things with long numbers... why? And is there a work around?

If you create the following function, and execute, you will get a return of: 11111111111111112. If you do much more, you will get exponential numbers. I just want to take long strings of numbers and place them into an array (the follow-up would be a split on the function). Is there anyway around this weirdness?

function sum2one(num) {
  var numtostring = num.toString();
  console.log(numtostring);
}

sum2one(11111111111111111);

Upvotes: 2

Views: 353

Answers (3)

guest271314
guest271314

Reputation: 1

I just want to take long strings of numbers and place them into an array

You can use Array.prototype.fill().

function sum2one(num, len, from, to, arr) {
  return  (arr 
          ? len > arr.length 
            ? (arr = [...arr, ...Array(len - arr.length)]) 
            : arr 
          : Array(len))
          .fill(num, from || 0, to || len)
}

let arr = sum2one(1, 17);

console.log(arr);

// set index 13

arr[13] = 2;

console.log(arr);

// fill indexes 14 through 21

arr = sum2one(3, 21, 14, 21, arr);

console.log(arr);

Upvotes: 0

teroi
teroi

Reputation: 1087

Javascript numbers are always 64-bit floating point numbers. That is why. That basically leads to the fact that for every number there is no exact integer representation.

So, in fact, toString() doesn't do the weird things. It is the actual format how the numbers are stored/represented/implemented in the javascript language.

What!? Is floating point math broken?! Not really, see Is floating point math broken?

Upvotes: 1

jdmdevdotnet
jdmdevdotnet

Reputation: 1

Javascript uses 64-bit floating point numbers.
I don't think it's possible to store precise numbers in javascript.

There are alternatives, bigint libraries can help. But you should just store as a string.

Upvotes: 0

Related Questions