Javascript 某些数字乘法运算不正确
Javascript multiplication is not working properly for some numbers
我在 JavaScript multiplication.I 中遇到了一个奇怪的行为,就是试图将数字乘以 100。
例如:
> 9.5*100
> 950
> 9.95*100
> 994.9999999999999
> 9.995*100
> 999.4999999999999
> 9.9995*100
> 999.9499999999999
> 9.99995*100
> 999.995
> 9.999995*100
> 999.9995
> 9.9999995*100
> 999.9999499999999
> 9.99999995*100
> 999.9999949999999
> 9.999999995*100
> 999.9999995
> 9.9999999995*100
> 999.99999995
> 9.99999999995*100
> 999.999999995
> 9.999999999995*100
> 999.9999999995
> 9.9999999999995*100
> 999.9999999999501
> 9.99999999999995*100
> 999.999999999995
> 9.999999999999995*100
> 999.9999999999994
我只想让数字像这样相乘
9.95*100
995.0 or 995
9.995*100
999.5
9.9995*100
999.95
9.9999995*100
999.99995
并且不是这样的
> 9.995*100
> 999.4999999999999
> 9.9995*100
> 999.9499999999999
> 9.9999995*100
> 999.9999499999999
浮点数相乘还有其他方法吗?
var factor = 100;
var number = 9.95;
var b = number.toString().split('.');
var answer = b[0]*factor+b[1]*(factor/(Math.pow(10,b[1].length)));
这是最糟糕的解决方案之一,但有效 :P
我在 JavaScript multiplication.I 中遇到了一个奇怪的行为,就是试图将数字乘以 100。 例如:
> 9.5*100
> 950
> 9.95*100
> 994.9999999999999
> 9.995*100
> 999.4999999999999
> 9.9995*100
> 999.9499999999999
> 9.99995*100
> 999.995
> 9.999995*100
> 999.9995
> 9.9999995*100
> 999.9999499999999
> 9.99999995*100
> 999.9999949999999
> 9.999999995*100
> 999.9999995
> 9.9999999995*100
> 999.99999995
> 9.99999999995*100
> 999.999999995
> 9.999999999995*100
> 999.9999999995
> 9.9999999999995*100
> 999.9999999999501
> 9.99999999999995*100
> 999.999999999995
> 9.999999999999995*100
> 999.9999999999994
我只想让数字像这样相乘
9.95*100
995.0 or 995
9.995*100
999.5
9.9995*100
999.95
9.9999995*100
999.99995
并且不是这样的
> 9.995*100
> 999.4999999999999
> 9.9995*100
> 999.9499999999999
> 9.9999995*100
> 999.9999499999999
浮点数相乘还有其他方法吗?
var factor = 100;
var number = 9.95;
var b = number.toString().split('.');
var answer = b[0]*factor+b[1]*(factor/(Math.pow(10,b[1].length)));
这是最糟糕的解决方案之一,但有效 :P