-2

I am trying to achieve what was asked in this question. In most scenarios, it is working fine by using the following code:

Math.round(num * 100) / 100

But I encountered a situation where it fails due to a very odd behavior. The number I'm trying to round is 1.275. I am expecting this to be rounded to 1.28, but it is being rounded to 1.27. The reason behind this is the fact that num * 100 is resulting in 127.49999999999999 instead of 127.5.

Why is this happening and is there a way around it?

EDIT

Yes, this question is probably the root cause of the issue I'm facing, but the suggested solutions of the selected answer are not working for me. The desired end result is a rounded number that is displayed correctly. So basically I'm trying to achieve what that question is instructing (check below) but I cannot figure out how.

If you just don’t want to see all those extra decimal places: simply format your result rounded to a fixed number of decimal places when displaying it.

Kassem
  • 8,116
  • 17
  • 75
  • 116
  • 4
    Possible duplicate of [How to deal with floating point number precision in JavaScript?](https://stackoverflow.com/questions/1458633/how-to-deal-with-floating-point-number-precision-in-javascript) – Jessica Aug 16 '18 at 11:44
  • see this too https://floating-point-gui.de/ – Edwin Aug 16 '18 at 11:49

1 Answers1

0

You can use toFixed to ensure the precision that you're looking for:

var x = 1.275;
var y = x * 100;
y = y.toFixed(1); // y = 127.5
Sean D
  • 134
  • 3