1

As you can see on this site, a usual way to calculate rounded number is: Math.round(num * 100) / 100

But my tests have shown me a strange behaviour of this method:

Math.round(1.155 * 100) / 100 = 1.16

Math.round(1.355 * 100) / 100 = 1.36

Math.round(1.255 * 100) / 100 = 1.25 - it's a mistake

Math.round(1.455 * 100) / 100 = 1.46

Math.round(0.255 * 100) / 100 = 0.26

Math.round(2.255 * 100) / 100 = 2.26

Math.round(3.255 * 100) / 100 = 3.26

Math.round(1.255 * 100) / 100 = 1.25 - it's a mistake

Be careful!

Valerii D
  • 11
  • 1
  • 1
    What's the question? – Mike Cluck Mar 28 '16 at 20:22
  • 1
    `1.255` is probably represented in binary floating point as a value *slightly* less than `1.255`. *edit* indeed - go to your console and type `1.255*100` and you'll get `125.4999999999999`. – Pointy Mar 28 '16 at 20:22
  • @Pointy I'm new at this and I don't understand your sentence about them being represented. `1.255` and `1.255` looks the same to me, so why are they represented differently in binary floating point? Thanks – jack blank Mar 28 '16 at 20:29
  • 1
    @jackblank read the linked explanation about binary floating point. Floating point values (which, in JavaScript, means all numbers) are represented internally as *binary* floating point values, not *decimal*. Some non-repeating decimal fractions are, in binary, *repeating* fractions. The notation `1.255` is text that is transformed into an internal numeric value by the parser, and (for some decimal values, like that one) that cannot be done exactly. – Pointy Mar 28 '16 at 20:32
  • 1
    Thanks for the answers! It's not a question. I said that Math.round(num * 100) / 100 not a rigorous mathematical solution. And I agee with a @Pointy in the explanation why. – Valerii D Mar 28 '16 at 20:42

0 Answers0