#23: (0.1+0.2).toFixed(2) and (1.005).toFixed(2)
Topic: numbers · Difficulty: ★★
console.log((0.1 + 0.2).toFixed(2));
console.log((1.005).toFixed(2));Output
0.30 1.00
Why
toFixed rounds the ACTUAL stored binary value, not the decimal you typed. 0.1 + 0.2 is really 0.30000000000000004 under the hood, and rounding that to 2 places correctly gives '0.30'. But 1.005 has no exact binary representation either — it's actually stored as slightly less than 1.005 (about 1.00499999999999989...), so rounding to 2 places rounds DOWN to '1.00' instead of the '1.01' you'd expect from ordinary decimal rounding. Both surprises trace back to the same root cause: floats can't represent most decimal fractions exactly.