trace(nHP);
trace(mHP);
trace(Math.round(nHP/mHP/0.0001));
trace(Math.round(nHP/mHP/0.0001)/100);
trace(Math.round(nHP/mHP/0.0001)*0.0001);
trace(Math.round(nHP/mHP/0.0001)*0.0001*100);
输出
127789
127834
9996
99.96
0.9996
99.96000000000001 // 为什么会这样?
再做测试:
trace(0.9996*100);
输出
99.96000000000001
这是一个已知两数求其百分比的问题,得到的数字时而会超长,关键是:
为什么0.9996*100得不到99.96?
因为0.9996是浮点数,浮点数并不能表示所有实数(程序中的0.9996可能是另外一个数字),浮点数的计算是不准确的。
能得到正确结果的方法如下:
(nValue/mValue*100).toFixed(2)
使用了Number的toFixed方法,该方法经过了舍入操作
(四舍五入)。