问题
Possible Duplicate:
Is JavaScript's Math broken?
I have a javascript and html code here my code
and i get a weird value when calculate specific fields. Only one checkbox has a script right now (the background music addon) and only when i select that add on with 1 of any of the 3in reels i get 24.990000000000002 in the total price. it's so weird its only with those inputs...it should be just 24.99....all the other inputs work and give accurate totals but just the 3 3in fields give those numbers...through trial and error I have found that the problem lies here
regthreetot = parseFloat(regthree * 50);
regfourtot = parseFloat(regfour * 100);
regfivetot = parseFloat(regfive * 200);
regsixtot = parseFloat(regsix * 300);
regseventot = parseFloat(regseven * 400);
supthreetot = parseFloat(supthree * 50);
supfourtot = parseFloat(supfour * 100);
supfivetot = parseFloat(supfive * 200);
supsixtot = parseFloat(supsix * 300);
supseventot = parseFloat(supseven * 400);
sixthreetot = parseFloat(sixthree * 50);
sixfourtot = parseFloat(sixfour * 100);
sixfivetot = parseFloat(sixfive * 200);
sixsixtot = parseFloat(sixsix * 300);
sixseventot = parseFloat(sixseven * 400);
the regthree,supthree and sixthree values are all multiplied by 50...all the other values are multiplied by a value with 3 digits...if i change 50 to 100 it will give a normal answer...why does the number of digits matter here and what can i do to fix it?
回答1:
It happens because of the way float arithmetic works. You can work around it by rounding to 2 decimal places (you won't be using fractions of a cent anyways): http://jsfiddle.net/vSsW9/1/
回答2:
Well until you get it figured out you can use Math.Round to round to two decimals. Assume your resulting var is called result, do result=Math.round(result*100)/100
回答3:
It's caused by float variables not being 100% accurate, to fix it to max 2 decimal points:
n.toFixed(2)
来源:https://stackoverflow.com/questions/11771718/weird-math-calculation