I am simply trying to round up 1.275.toFixed(2)
and I was expecting a return of 1.28, rather than 1.27.
Using various calculators and the simple method of rounding to the nearest hundredth, if the last digit is greater than or equal to five, it should round up.
If this doesn't work with toFixed(2), how would it?
People asking whether console.log(1.275.toFixed(2)) prints off 1.28, here's a quick screenshot MacOS Chrome Version 55.0.2883.95 (64-bit)
The 1.275
base 10 number has finite digits but becomes periodic when converted to base 2:
= 0b1.01000110011001100110011001100110011001100110011010
^^^^
Since it has infinite digits, it cannot be represented exactly in a computer unless you use an arbitrary precision library (a library than represents numbers as text to keep them in base 10). JavaScript numbers do not use such library for performance reasons.
Since the original value has already lost precision when it reaches JavaScript, rounding it will not improve that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With