2

JavaScript stores all numbers in double-precision floating-point format, with a 52-bit mantissa and an 11-bit exponent (the IEEE 754 Standard for storing numeric values), and therefore its Number-to-String conversions are often inaccurate. For instance,

111111111*111111111===12345678987654321

is correct, but

(111111111*111111111).toString()

returns "12345678987654320" instead of "12345678987654321". Likewise, 0.362*100 yields 36.199999999999996.

Is there a simple way to accurately convert numbers to strings?

1 Answer 1

3

It is NOT the number to string conversion that is inaccurate. It is the storage of the number itself in floating point as all values cannot be represented precisely in floating point and there is a limit to the number of significant digits that can be stored (about 16). You simply can't use floating point if you need perfect precision and you certainly can't be using a number that has this many significant digits. Alternatives are integers, binary coded decimals, big decimal libraries, etc...

Here's a simple demo of the problem representing certain values in floating point: http://jsfiddle.net/jfriend00/nv4MJ/

Depending upon what problem you are actually trying to solve, decimal precision issues can often be worked around by using toFixed(n) when converting to display.

Other references to read for more explanation:

How to deal with floating point number precision in JavaScript?

Why can't decimal numbers be represented exactly in binary?

What range of numbers can be represented in a 16-, 32- and 64-bit IEEE-754 systems?

Why Floating-Point Numbers May Lose Precision - MSDN - Microsoft

Is floating point math broken?

Accurate floating point arithmetic in JavaScript

https://stackoverflow.com/questions/744099/is-there-a-good-javascript-bigdecimal-library

Sign up to request clarification or add additional context in comments.

2 Comments

Worth pointing out that console.log((12345678987654321).toString()); gives us "12345678987654320", and that 12345678987654321 === 12345678987654320 is true.
That is greater than MAX_INTEGER, stackoverflow.com/questions/307179/…

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.