1

.29 * 100 = 28.999999999999996 in js so what's the simplest and most reliable way to multiply decimals in js to ensure that .29 * 100 = 29?

user7066345
  • 427
  • 1
  • 5
  • 10
  • 2
    The best way is not to use the decimals. – Rajaprabhu Aravindasamy Nov 03 '16 at 18:49
  • Take a look at [floating-point-gui.de](http://floating-point-gui.de/). This should explain why you get these 'wrong' values and how to work around them. – Aurora0001 Nov 03 '16 at 18:50
  • In the realm of reasonable numbers, if you don't use a dedicated lib to do it for you, the usual practice is to use whole units (e.g., `29 * 10000`), and then convert to that two-places form for display. – T.J. Crowder Nov 03 '16 at 18:51
  • Depending on how _accurate_ you want it and what magnitude of numbers you want to work with, this might not work for you but for most general cases it does - 1. convert from decimal to integer by working out the decimal places and multiplying by 10^(amount) 2. use `Math.round()` to get the actual number 3. do more math 4. convert back to the previous amount of decimal places 5. round to the expected precision. It's not perfect, but works if you're not that interested in accuracy as you usually end being off by a bit. – VLAZ Nov 03 '16 at 18:56
  • @vlaz: There are lots of gotchas in that, not least because some numbers that look like they should round up actually round down. For instance: `Math.round(0.565 * 100)` is `56`, not `57`. Why? Because `0.565 * 100` is `56.49999999999999`. More fun reading: http://stackoverflow.com/questions/1726630/formatting-a-number-with-exactly-two-decimals-in-javascript – T.J. Crowder Nov 03 '16 at 19:37
  • @T.J.Crowder with my suggestion you'd do `0.565 * 1000` and round. The idea is to remove all decimal places before manipulating it further. Again, it's not a _perfect_ solution, it's going to work for a lot of general cases, when you want to calculate something and show it to the user and where you're not really concerned with accuracy. It will also fail with really small and really large numbers (really small as they'd be transformed to really large) but for something up to a million-ish and with 2-4 decimal places, it's workable. – VLAZ Nov 03 '16 at 19:45

0 Answers0