2

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);

10
  • 1
    blame the IEEE, and just store strings...
    – dandavis
    Jan 23, 2017 at 20:54
  • I think this is just a matter of the nature of the one Number type in javascript? For really big numbers I think scientific notation is probably a better way to go about it? @dandavis, are you sure storing strings as opposed to an actual number is a safe way to go (what happens if you need to perform arithmetic operations with those stored strings)? Jan 23, 2017 at 20:55
  • or check a big number implementation (it might be slow, but you will be able to perform calculation on them and get consistent string representation) Jan 23, 2017 at 20:56
  • Related, though at the other end of the spectrum. Jan 23, 2017 at 21:01

3 Answers 3

1

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?

2
  • 1
    Thank you very much. Very much appreciated Jan 23, 2017 at 21:08
  • 1
    Would have loved to. It won't let me upvote until I got a high enough reputation. Jan 26, 2017 at 6:01
0

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.

0

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);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.