Why am I getting the wrong division answer?

Super simple - I'm running a useEffect function in React. I need to do a simple calculation, but I keep getting the wrong answer.

Example, I get 10 as an answer instead of the expected 8,960...

I thought it might be a string and not an Int at first, but it made no difference.

const price = 5.58;
console.log(price); // returns 5.58
const money = 50.00;
console.log(money); // returns 50
const dev = parseInt(money) / parseInt(price);
console.log(dev) // returns 10 ???.

I expected it const dev to return 8,960573476702509 but it returned 10

Answers:

Answer

You're doing division between two integers, as parseInt(50.00) will give 50 and parseInt(5.58) gives 5, so your calculation will be doing 50/5 which is equal to 10. To perform math with your floating-point numbers, there is no need to parse them as they're already floats:

const price = 5.58; // already a float
console.log(price); // returns 5.58
const money = 50.00; // already a float
console.log(money); // returns 50
const dev = money / price;
console.log(dev) // 8.960573476702509

Answer

You need to use parseFloat as you are dealing with decimal number

const price = 5.58;
console.log(price); 
const money = 50.00;
console.log(money); 
const dev = parseFloat(money) / parseFloat(price);
console.log(dev)

Answer

const price = 5.58;
console.log(price); // returns 5.58
const money = 50.00;
console.log(money); // returns 50
const dev = money / price;
console.log(dev) // returns 10 ???.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.