How could it get a round 0.17 instead of 0.18 from 0.175?
Asked
Active
Viewed 117 times
0

Sheldon Wei
- 1,198
- 16
- 31
-
https://stackoverflow.com/questions/588004/is-floating-point-math-broken – j08691 Sep 14 '18 at 03:13
-
https://stackoverflow.com/questions/18374940/why-tofixed-rounding-is-so-strange – j08691 Sep 14 '18 at 03:15
2 Answers
1
It doesn't work insanely. You tell the function to keep two decimal digits and that's what it does. If you want to round your number, you can try multiplying your number with 10^x
, using Math.round
and then dividing by the same number:
const roundToDecimals = function (number, decimals) {
const num = Math.pow(10, decimals);
return Math.round(number * num) / num;
}
console.log(roundToDecimals(0.175, 2));

Angel Politis
- 10,955
- 14
- 48
- 66
-
2That's just replacing one form of rounding error with a different one that coincidentally rounds the way you expected; the fundamental problem still exists, and will bite you with some other input. The fundamental problem is that `0.175` doesn't actually exist; that literal is just a short hand for `0.1749999999999999...`, which is closer to `0.17` than `0.18`, and *should* round to `0.17`. `(0.195).toFixed(2)` rounds to `0.20` because `0.195` is really `0.195000000000000006...` and therefore closer to `0.20` than `0.19`. – ShadowRanger Sep 14 '18 at 03:21
0
You have told to round it till 2 points .so the answer will be 0.17 because the third number is less than or equal to 5.

Prabha Pandey
- 29
- 3
-
Actually, if the third digit were really, exactly 5, it would round up (AFAICT, for numbers that floating point can represent precisely, it rounds away from zero, which is odd, but whatever). The problem is that 0.175 isn't precisely representable, it's more like `0.1749999999999999...`, so the final digit is *slightly* less than 5, and therefore gets rounded down. – ShadowRanger Sep 14 '18 at 05:59