1

I have a number 0.780000000000000016 (18 digits after decimal point, type 'number')

I need to convert it to string.

If I make 0.780000000000000016.toPrecision(18) it returns "0.780000000000000027"

What to do?

Rattrap
  • 295
  • 4
  • 13
  • Possible duplicate of [How to deal with floating point number precision in JavaScript?](https://stackoverflow.com/questions/1458633/how-to-deal-with-floating-point-number-precision-in-javascript) – Peter B Nov 08 '17 at 10:58
  • The extra 0.000000000000000016 might have been due to floating point rounding errors (as would the change in the number at the end). Do you absolutely need to have it to 18 decimal places, or would rounding it to a precision that showed 0.78 be enough? – bouteillebleu Nov 08 '17 at 10:59
  • Yes, I need all 18 decimal places – Rattrap Nov 08 '17 at 11:00
  • The number type is not accurate enough for that many digits. You can't have 0.78000...16 as a number, it has to be a string to start with (or a custom object). – JJJ Nov 08 '17 at 11:03
  • And how to convert it to string then? – Rattrap Nov 08 '17 at 11:04
  • You can't "convert" it because it doesn't have the accuracy if it starts as a number. If you now have `var a = 0.78...16` change it to `var a = "0.78...16"`. – JJJ Nov 08 '17 at 11:08
  • The closest JavaScript number (IEEE 754 64-bit binary float) to 0.780000000000000016 is 0.7800000000000000266453525910037569701671600341796875. The result you got is just as short as your input, and closer to the actual value. – Patricia Shanahan Nov 08 '17 at 14:35

0 Answers0