0

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?

4

3 回答 3

0

它的发生是因为浮点算术的工作方式。您可以通过四舍五入到小数点后 2 位来解决它(无论如何您都不会使用一分钱):http: //jsfiddle.net/vSsW9/1/

于 2012-08-02T05:55:15.670 回答
0

好吧,直到你弄清楚你可以使用 Math.Round 来四舍五入到小数点后两位。假设你的结果变量被称为结果,做result=Math.round(result*100)/100

于 2012-08-02T05:56:04.610 回答
0

It's caused by float variables not being 100% accurate, to fix it to max 2 decimal points:

n.toFixed(2)
于 2012-08-02T07:05:48.407 回答