Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Round error

I have a problem with rounding numbers.

x = 0.175;
console.log(x.toFixed(2));
// RESULT: 0.17

x = 1.175;
console.log(x.toFixed(2));
// RESULT: 1.18

x = 2.175;
console.log(x.toFixed(2));
// RESULT: 2.17

Why is (X!=1).175 not rounded to X.18?

like image 299
Jean Paul CP Avatar asked Apr 19 '26 23:04

Jean Paul CP


1 Answers

The problem here is that 0.175 is a repeating decimal in binary (specifically, after a short prefix, it settles down to a repeating 0011 pattern). When represented in a finite floating point representation, this repeating pattern gets truncated. When you change the integer part from 0 to 1 to 2, you are adding one additional bit each time to the integer part of the number, which pushes off one trailing bit. Depending on what bit value gets pushed off, that can change the rounded value enough to affect the visible result. Note that after 2.175, the next change in rounding behavior doesn't occur until 8.175 (after two more low-order bits have been pushed off the representation).

like image 111
Ted Hopp Avatar answered Apr 21 '26 12:04

Ted Hopp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!