是否有比使用*
和更好的方法来乘以和除数字/
?
使用这些操作符的Chrome Firefox和Internet Explorer中存在一种奇怪的行为:
x1 = 9999.8
x1 * 100 = 999979.9999999999
x1 * 100 / 100 = 9999.8
x1 / 100 = 99.99799999999999
Run Code Online (Sandbox Code Playgroud)
我想本轮下跌与用户输入parseInt ( x1 * 100 ) / 100
,结果为9999.8
是9999.79
我应该用另一种方式来实现这个目标吗?
那不是错误.您可以查看:
浮点中的整数算术是精确的,因此可以通过缩放来避免十进制表示错误.例如:
x1 = 9999.8; // Your example
console.log(x1 * 100); // 999979.9999999999
console.log(x1 * 100 / 100); // 9999.8
console.log(x1 / 100); // 99.99799999999999
x1 = 9999800; // Your example scaled by 1000
console.log((x1 * 100) / 10000); // 999980
console.log((x1 * 100 / 100) / 10000); // 9999.8
console.log((x1 / 100) / 10000); // 99.998
Run Code Online (Sandbox Code Playgroud)