Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stange functionality in javascript numbers [duplicate]

Tags:

javascript

Possible Duplicate:
Large numbers erroneously rounded in Javascript

I am experiencing some strange behavior when working with numbers in javascript. When I use the following code:

<a href="javascript:console.log({'id':9200000000032337}.id);"> CLICK HERE </a>

I get the number 9200000000032336 in my console. I think it most be something with rounding or max values for numbers, but I don't understand it completely. Anyone?

like image 464
Jan Salvador van der Ven Avatar asked Dec 20 '22 14:12

Jan Salvador van der Ven


1 Answers

I'm not a Javascript expert, but it sounds like your number is being stored as an IEEE-754 64-bit floating point number. Certainly that's what I get from C# code which will display the exact value of a double:

double d = 9200000000032337;
Console.WriteLine(DoubleConverter.ToExactString(d));

(Using my own DoubleConverter class.) My output is the same as yours: 9200000000032336

Floating point values only ever hold a certain number of significant digits accurately - and when the numbers get high enough, even integers can't be stored exactly.

ECMA-262 seems to confirm this:

4.3.19
Number value
primitive value corresponding to a double-precision 64-bit binary format IEEE 754 value

and from section 7.8.3 (numeric literals):

A numeric literal stands for a value of the Number type. This value is determined in two steps: first, a mathematical value (MV) is derived from the literal; second, this mathematical value is rounded as described below.

Section 8.5 contains more details.

like image 59
Jon Skeet Avatar answered Jan 06 '23 11:01

Jon Skeet