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?

string QNA
  • 3,110
  • 3
  • 17
  • 14

1 Answers1

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

Community
  • 1
  • 1
jfriend00
  • 683,504
  • 96
  • 985
  • 979
  • 2
    Worth pointing out that `console.log((12345678987654321).toString());` gives us `"12345678987654320"`, and that `12345678987654321 === 12345678987654320` is `true`. – T.J. Crowder Apr 21 '13 at 12:36
  • That is greater than MAX_INTEGER, http://stackoverflow.com/questions/307179/what-is-javascripts-max-int-whats-the-highest-integer-value-a-number-can-go-t – Xotic750 Apr 21 '13 at 12:38