toFixed() incorrect output

43 views
Skip to first unread message

Ahmed Suror

unread,
Mar 24, 2022, 6:35:43 PM3/24/22
to v8-dev
By looking into this example:
var x = 1.245;
var xFixed = x.toFixed(2);
xFixed value should be 1.25
but it is printing 1.24

Robert Paveza

unread,
Mar 25, 2022, 12:04:35 PM3/25/22
to v8-dev
Check out the description of toFixed on MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed

It doesn't cover your specific example, but it does cover the differences between, e.g., Number(2.35).toFixed(1) and Number(2.55).toFixed(1).

The TL;DR here is that floating point numbers are represented in a non-intuitive way internally to your computer (IEEE 754), and the toFixed function doesn't take the time to perform the rounding in the way you expect. You can generally achieve the rounding you want my multiplying your number by a factor (in your case, 100), calling Math.round() on the result, dividing it again by the same factor used previously, and then formatting that with toFixed().

Ahmed Suror

unread,
Mar 28, 2022, 5:06:03 PM3/28/22
to v8-dev
Thanks very much for your help.

Feng Yu

unread,
Apr 16, 2022, 10:24:42 AM4/16/22
to v8-dev
on my computer, it does pirnt 1.25.

Xnip2022-04-16_22-24-09.jpeg
Reply all
Reply to author
Forward
0 new messages