Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why does subtracting decimals not work in javascript

Please don’t downvote this because of me writing it badly, I don’t really know how to explain this. But, 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.
Please help me if you can.
Thanks.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading