Search code examples
javascriptdecimalpromptsubtraction

Why does subtracting decimals not work in javascript


If I do the code below and enter a decimal for one or both of the numbers, lets says I use 0.5 and 0.3, I should get 0.2 but I get 0 only. This makes no sense at all to me, it is probably a problem with using prompt but I need to use prompt or a method that is similar to prompt(I'm using sweetalert2 input for the alert). I am okay with using any js libraries.

const x = parseInt(prompt('1'))
const y = parseInt(prompt('2'))
alert(x-y)

I know it is a weird problem, but I don't know how to fix it.


Solution

  • You need to use parseFloat, not parseInt. parseInt is whole numbers only, while parseFloat allows decimal places.

    parseFloat('0.9') === 0.9
    parseInt('0.9') === 0