1

I'm trying to format 65.32 to become 6532

65.32 * 100 gets me 6531.999999999999.

Why does it do that? Is it a bug? Should I change it to a string and use string manipulation instead?

Harry
  • 52,711
  • 71
  • 177
  • 261
  • 1
    welcome to the wonderful world of 64 bit arithmetic. – Nina Scholz May 08 '19 at 20:45
  • 1
    Possible duplicate of [Is floating point math broken?](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) – Ivar May 08 '19 at 20:45
  • 1
    Depends on what you're doing, but you could just treat as a string and a remove the period ? – adeneo May 08 '19 at 20:46
  • @Ivar thanks got it on the why, what's the most recommended solution? I can treat it as a string and remove the period yeah. Is that the way to go? – Harry May 08 '19 at 20:47
  • @Harry Like adeneo said, it depends on what you are doing. You can use `.toFixed()` as [mentioned here](https://stackoverflow.com/questions/21472828/js-multiplying-by-100-giving-wierd-result) ([and here](https://stackoverflow.com/questions/21693552/wrong-value-after-multiplication-by-100), [and here](https://stackoverflow.com/questions/14490496/how-to-multiply-in-javascript-problems-with-decimals)). That being said, I get the same result on Firefox and Edge. It doesn't seem to be Chrome specific. – Ivar May 08 '19 at 20:57

1 Answers1

1

Generally speaking, if you're dealing with numbers it's usually better to stick with numbers. It makes your code more readable and easier to follow. The Math library provides what you need.

var x = 62.29933;
console.log(x*100);
x = Math.floor(62.29933*100);
console.log(x);
x = Math.ceil(62.29933*100);
console.log(x);
x = Math.round(62.29933*100);
console.log(x);
DCR
  • 14,737
  • 12
  • 52
  • 115