Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Incorrect multiplication answer

Tags:

javascript

I understand that JS math is not perfect. but how can i format this to get the correct answer as I have a cart item which costs .60 cents and they can change the quantity?

var a=3*.6;
document.write(a);

writes 1.7999999999999998

Obviously I want to write 1.8. any ideas how to accomplish this?

like image 415
Johnny Craig Avatar asked Dec 10 '22 05:12

Johnny Craig


2 Answers

Use toFixed to round it back:

var a = 3*.6;
document.write(a.toFixed(2));

If you need it as a number, add a + sign before it:

var a = 3*.6;
console.log(+a.toFixed(2)); // Logs: 1.8, instead of "1.80"
like image 192
Joseph Silber Avatar answered Jan 04 '23 20:01

Joseph Silber


var a=3*.6;
a = Math.round(a*10)/10;
document.write(a);

Since you want to round to the 10ths place, you need to multiply the number by 10, round the result of that multiplication to the nearest whole number, and then divide the result by 10.

It's not sexy, but ya gotta do whatchya gotta do.

like image 37
Cory Danielson Avatar answered Jan 04 '23 19:01

Cory Danielson