Incorrect multiplication answer
I understand that JS math is not perfect. but how can i format this t开发者_StackOverflow社区o 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?
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"
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.
var a=(3*(.6*100))/100;
document.write(a);
Example: http://jsfiddle.net/aJTJq/
- multiply .6 by 100 to get the 60 cents
- multiply that by 3
- divide it by 100 to return it as a dollar figure
Write the .6 as a fraction: a=3*6/10
and you get 1.8
As a more general rule, you could try rounding to the nearest millionth with
Math.round(result*1000000)/100000
and seeing what that gets you.
What you want to do is have some type of rounding function.
Try this: Rounding Function
<script language="javascript" type="text/javascript">
function roundNumber(rnum, rlength) { // Arguments: number to round, number of decimal places
var newnumber = Math.round(rnum*Math.pow(10,rlength))/Math.pow(10,rlength);
document.roundform.numberfield.value = parseFloat(newnumber); // Output the result to the form field (change for your purposes)
}
</script>
And then something like this to call the function
<form name="roundform">
<input type="text" name="numberfield" value="">
<input type="button" value="Round" onClick="roundNumber(numberfield.value, 2);">
</form>
This example just takes a number in the text field and ensures that it is rounded to two decimal places.
This was taken from http://www.mediacollege.com/internet/javascript/number/round.html
There are more examples on this link as well. Hopefully this helps. Cheers
精彩评论