I have a string:
"{0:16970861903381446063,length:1}"
I tried converting it to an object using the eval method, but it also evaluates the string and hence rounds the numerical value, returning:
{0:16970861903381447000,length:1}
I tried passing the number as a string before calling eval on it,
using 16970861903381446063 + '' as the value when creating the JSON string; checking it with typeof shows it as being of type string, but it still rounds the number 16970861903381446063 to 16970861903381447000.
Is there a way I can bypass this, or a better way to do this?
Following is the code that generates the json text from an array containing the numbers
function simplify(arr){
request = "{";
if (arr.length ==1){
request += 0 + ":" + (arr[0] + '') + "," ;
}
else{
for (var i=0;i<=arr.length-1 ;i++){
request += i + ":" + (arr[i] + '') + ",";
}
}
request += "length" + ":" + arr.length +"}";
return request;
}
You’re running up against the precision of an IEEE double-precision float, which uses 53 bits for the mantissa and 11 bits for the exponent.
Javascript numbers, ALL of them, are represented by 64-bit floating point numbers. Floating point numbers in many languages are represented by two parts, a mantissa and an exponent. In Javascript, the mantissa is 53 bits, and the exponent is 11 bits.
When you see numbers expressed as, for example, 3.5346367e+22, the mantissa is 3.5246367, and the exponent is 22.
The numbers you are trying to store are larger than the maximum value of the mantissa, so your numbers get rounded, and larger numbers get an exponent.
Long story short, unless you’re doing arithmetic operations with these huge numbers, you should store them as a string.
Lastly, you should expressed JSON Arrays as actual JSON Arrays, and not as objects that pretend to be arrays by defining integer keys and a length property: