parseFloat 的奇怪问题,怎么精度不对???

ln_boy 2003-08-29 04:30:14

下面代码是对16个文本框取值parseFloat()再相加:

假如所有的框全部输入0.9,则而得到的结果是14.400000000000004。


为什么??????

<script>
function Chgjj1()
{
document.fresume.jj1.value=parseFloat(document.fresume.jj11.value)
+parseFloat(document.fresume.jj21.value)+parseFloat(document.fresume.jj31.value)
+parseFloat(document.fresume.jj41.value)+parseFloat(document.fresume.jj51.value)
+parseFloat(document.fresume.jj61.value)+parseFloat(document.fresume.jj71.value)
+parseFloat(document.fresume.jj81.value)+parseFloat(document.fresume.jj91.value)
+parseFloat(document.fresume.jj101.value)+parseFloat(document.fresume.jj111.value)
+parseFloat(document.fresume.jj121.value)+parseFloat(document.fresume.jj131.value)
+parseFloat(document.fresume.jj141.value)+parseFloat(document.fresume.jj151.value)
+parseFloat(document.fresume.jj161.value);
}
</script>

<form name=fresume>
1<input type=text name=jj1><br>

11<input type=text name="jj11" value=0 onChange="javascript:Chgjj1();"><br>
21<input type=text name="jj21" value=0 onChange="javascript:Chgjj1();"><br>
31<input type=text name="jj31" value=0 onChange="javascript:Chgjj1();"><br>
41<input type=text name="jj41" value=0 onChange="javascript:Chgjj1();"><br>
51<input type=text name="jj51" value=0 onChange="javascript:Chgjj1();"><br>
61<input type=text name="jj61" value=0 onChange="javascript:Chgjj1();"><br>
71<input type=text name="jj71" value=0 onChange="javascript:Chgjj1();"><br>
81<input type=text name="jj81" value=0 onChange="javascript:Chgjj1();"><br>
91<input type=text name="jj91" value=0 onChange="javascript:Chgjj1();"><br>
101<input type=text name="jj101" value=0 onChange="javascript:Chgjj1();"><br>
111<input type=text name="jj111" value=0 onChange="javascript:Chgjj1();"><br>
121<input type=text name="jj121" value=0 onChange="javascript:Chgjj1();"><br>
131<input type=text name="jj131" value=0 onChange="javascript:Chgjj1();"><br>
141<input type=text name="jj141" value=0 onChange="javascript:Chgjj1();"><br>
151<input type=text name="jj151" value=0 onChange="javascript:Chgjj1();"><br>
161<input type=text name="jj161" value=0 onChange="javascript:Chgjj1();"><br>
</form>
代码如上,求jj11至jj161的和,显示在jj1中,但是有错误。
举例来说,jj11至jj161全部输入0.9,则jj1中显示的是14.400000000000004。

...全文
643 2 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
ydr2002 2003-08-29
  • 打赏
  • 举报
回复
JS浮点运算存在不精确问题,弥补的办法是转化为整形运算再转为浮点型。记得在本版看过有关方面的贴子。
dragon2006 2003-08-29
  • 打赏
  • 举报
回复
你必须要这样,才能实现:
<script>
alert(parseFloat(12.44644).toFixed(2));
</script>
想要精确到几位,就tofixed几

87,997

社区成员

发帖
与我相关
我的任务
社区描述
Web 开发 JavaScript
社区管理员
  • JavaScript
  • 无·法
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧