aphex
aphex

Reputation: 3412

Convert large number in javascript

After pasting the number t=3.7333333258105216E16 in jsconsole.com or in Web Inspector, I get 37333333258105220.

parseFloat(3.7333333258105216E16) gives the same result.

What is the reason ?

Upvotes: 0

Views: 374

Answers (3)

Briguy37
Briguy37

Reputation: 8402

JavaScript represents numbers as floats. This storage format consists of 64 bits. One bit is for the sign, 11 bits are for the power of 10 to multiply the number by, and 52 bits are for the number.

Because of the above, numbers can be acurate to the 1/2^52, or 1 / 4,503,599,627,370,496. Thus, numbers are accurate to within this fraction. Check out this wikipedia page for more information on floating point numbers.

I tested this out by trying to add one to 4,503,599,627,370,495. It gets to 4,503,599,627,370,496, but does not get past it. Here's the fiddle for testing.

Upvotes: 3

Dennis
Dennis

Reputation: 32598

You can't always accurately represent a floating point decimal number in binary. It is losing precision at the end of the number so it can fit in 64 bits.

Upvotes: 1

Wyatt
Wyatt

Reputation: 1366

You are encountering floating-point roundoff. JavaScript numbers are implemented as double precision, 64-bit floats according to the IEEE 754 standard.

Upvotes: 2

Related Questions