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

parseFloat causing weird calculations

I have a function that needs to find the difference between 3 numbers. They can come in as strings, so I need to use parseFloat and maintain 2 decimal places. When I use parseFloat with negative numbers, I’m getting weird differences though.

// This will output -0.004999999999636212
let temp = -8985.69 - -8985.915 - 0.23
console.log(temp);

// But this will output -4.365674488582272e-13
let x = -8985.69
let y = -8985.915
let z = 0.23
let temp2 = parseFloat(x.toFixed(2)) - parseFloat(y.toFixed(2)) - parseFloat(z.toFixed(2))
console.log(temp2);

I was looking at the parseFloat docs and I see the part where the conversion may get changed when an invalid character is encountered. But I’m not seeing any wrong characters here and I’m not getting how the parsing stopping at any point would cause it to equal -4.365674488582272e-13

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 second number has three decimal places and you set it toFixed(2) so it changes its value to -8985.92. When I use .toFixed(3) for it I get the first result you are looking for.

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