虽然提供了一个answer to a question关于添加一个方法,增加一个HTML值的浮动值在input
,我遇到了我所知道的是common issue with IEEE Floating point math。这是我所看到的例子(用demo):为什么JavaScript中的parseFloat()会产生consisant但会产生单元结果?
<input type="text" name="BoqTextBox" id="BoqTextBox" value="0.001" />
<input type="Button" id='AddButton' value="+" />
<script>
$('#AddButton').on('click', function() {
var input = $('#BoqTextBox');
input.val(parseFloat(input.val(), 10) + 1);
})
</script>
点击+
键,使输入的第一个这样的递增(使用本converter为IEEE二进制表示):
S| Exp | Mantissa
0.001 //0 0111 0101 000 0011 0001 0010 0110 1111
1.001 //0 0111 1111 000 0000 0010 0000 1100 0101
2.001 //0 1000 0000 000 0000 0001 0000 0110 0010
3.001 //0 1000 0000 100 0000 0001 0000 0110 0010
4.0009999999999994 //0 1000 0001 000 0000 0000 1000 0011 0001
5.0009999999999994 //0 1000 0001 010 0000 0000 1000 0011 0001
6.0009999999999994 //0 1000 0001 100 0000 0000 1000 0011 0001
7.0009999999999994 //0 1000 0001 110 0000 0000 1000 0011 0001
8.001 //0 1000 0010 000 0000 0000 0100 0001 1001
9.001 //0 1000 0010 001 0000 0000 0100 0001 1001
10.001 //0 1000 0010 010 0000 0000 0100 0001 1001
... then predictably like this until ...
15.001 //0 1000 0010 111 0000 0000 0100 0001 1001
16.000999999999998 //0 1000 0011 000 0000 0000 0010 0000 1100
17.000999999999998 //0 1000 0011 000 1000 0000 0010 0000 1100
18.000999999999998 //0 1000 0011 001 0000 0000 0010 0000 1100
19.000999999999998 //0 1000 0011 001 1000 0000 0010 0000 1100
... then predictably like this until ...
31.000999999999998 //0 1000 0011 111 1000 0000 0010 00001100
32.001 //0 1000 0100 000 0000 0000 0001 00000110
33.001 //0 1000 0100 000 0100 0000 0001 00000110
... then predictably like that up to 256 (a power of 8 seemed fitting to test) ...
我还不知道为什么这种行为表现在这些特定的价值观上,我可以采取什么逻辑步骤来缓解其影响?四舍五入显示目的,同时保持实际计算的值存储在其他地方?
我会一轮显示 – 2013-03-22 20:02:04
@JanDvorak我敢肯定,有没有其他的解决方案... – 2013-03-22 20:05:45
@JuanMendes'BigDecimal' – 2013-03-22 20:06:52