0

I was breaking my head debugging the rounding in some application and it boiled down to this:

(1.445).toFixed(2) // rounding as expected = 1.45
"1.45"
(85.485).toFixed(2) // what??? should be 85.49!
"85.48"

The number itself 85.485 can be displayed as such, so it doesn't seem a power of 2 float problem...

Any Idea why this is happening?

estani
  • 24,254
  • 2
  • 93
  • 76
  • Like @JaromandaX said, be careful when using [`toFixed`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed) when dealing with numbers that need precision. Use [`toPrecision`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toPrecision) instead. – FF- Dec 10 '19 at 12:27
  • @FF - toPrecision is not going to help – Jaromanda X Dec 10 '19 at 12:28
  • @JaromandaX care to elaborate? – FF- Dec 10 '19 at 12:29
  • Just avoid using floats or doubles if you need such precision. Use integers and trail as needed to avoid undesired results. – briosheje Dec 10 '19 at 12:31
  • how would you use toPrecision in both cases ... 85.485.toPrecision(2) gives 85 ... oh, so it's total digits ... 85.485.toPrecision(4) gives .... 85.48 ... still haven't found what OP is looking for ... and then, you need to calculate the value for the argument based on the number of digits before the decimal point ... but, as mentioned the result still won't give the "expected" 85.49 – Jaromanda X Dec 10 '19 at 12:31
  • 1
    To display formatted numbers nowadays, I recommend the `Intl.NumberFormat` constructor... `const formatter = new Intl.NumberFormat('en', { minimumFractionDigits: 2, maximumFractionDigits: 2 }); console.log(formatter.format(1.445));` – Christian C. Salvadó Dec 10 '19 at 12:32
  • @FF- according to (this)[https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toPrecision] `toFixed` relies on `toPrecision`. – estani Dec 10 '19 at 13:29
  • Number `85.485`does not exist. On scanning it is rounded to the nearest existing number `85.4849999999999994` (you can proof it with `(85.485).toPrecision(18)`). And rounding this number results in the correct value of `"85.48"` (a string, because the number does not exists!). – Wiimm Dec 13 '19 at 12:45

0 Answers0