-1

Currently have a formula which essentially looks like this:

Math.round((20.49-14.99)*5);

The resulting number is 27.5 and AFAIK, Math.round() should round UP if the number is 0.5 and above and round down if it is below. Unless I've misunderstood, I was assuming the result would be rounded up to 28 (as it does in Microsoft Excel, for example), but instead, it rounds down to 27.

At first I assumed it had something to do with my code, but when I console logged it, the result was exactly the same.

Am I missing something and if I have, how would I round-up from 0.5 onwards?

finnmglas
  • 1,626
  • 4
  • 22
  • 37
jimjamjosh
  • 15
  • 5
  • 1
    Well, it's fun when it comes to js math, check the result of `20.49-14.99`, you can jsut type it in console and see the magic – Huangism Jan 27 '20 at 16:18
  • (20.49-14.99)*5 = 27.499999999 which rounds to 27 because of how IEEE-754 floating values are handled. – ruby_newbie Jan 27 '20 at 16:19
  • `(20.49-14.99)*5` evaluates to `27.499999999999`, not `27.5`, due to how floating point values are handled. –  Jan 27 '20 at 16:19
  • 3
    @ruby_newbie It's not "because JavaScript", it's because of that's how IEEE-754 floating-point values works. Other languages will exhibit this same behavior. –  Jan 27 '20 at 16:19
  • This occurs because `14.99` and `20.49` cannot be represented exactly in binary. –  Jan 27 '20 at 16:30
  • Thanks for pointing this out. I always assumed it just rounded up. This totally answers the question for me. For anyone that stumbles upon a similar issue, the solution that worked for me is adding `myvariable.toFixed(2)` which rounds up and gives me the desired result! – jimjamjosh Jan 27 '20 at 16:32

2 Answers2

1

Due to the way floating points work, the result of (20.49-14.99)*5 is actually 27.499999999999993, which is closer to 27 than 28

Adam Bowles
  • 32
  • 1
  • 5
0

(20.49-14.99)*5 is 27.499999999999993, so JavaScript will round this to closer value. You should use Math.ceil to round above value

Ahmet Zeybek
  • 1,196
  • 1
  • 13
  • 24
  • Currently using this formula to display prices and ceil(or floor) is not going to accurately represent the Excel Spreadsheet I recieved. Personally, I have no issues with it rounding accurately (which it is), but apparently, the disparency with the Spreadsheet is an issue. – jimjamjosh Jan 27 '20 at 16:24