0

Let's have an input type text field. Now type into 4444.40, get the input value in JS, multiply by 100, and try to obtain exactly 444440. No chance. Just try this:

let num = 4444.40
let multiplied = num * 100
console.log(multiplied)

You will get 444439.99999999994. How to solve this?

Vladislav Ladicky
  • 2,261
  • 1
  • 11
  • 13
  • 1
    That's how floating point numbers work. What's the overall context/goal? – Felix Kling Jun 14 '21 at 13:32
  • For anyone that wants to know why this happens: [Is floating point math broken?](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) – Reyno Jun 14 '21 at 13:34

1 Answers1

0

This is how floating point math works in JavaScript. You'll need to round the product to get a whole number.

To get more precise, first multiply by a larger factor (say 10,000), then round that and then divide back down by the same amount.

let num = 4444.40
let multiplied = num * 100
num = Math.round(multiplied);
console.log(num)
Scott Marcus
  • 64,069
  • 6
  • 49
  • 71