关于浮点数问题

netfound 2004-09-27 11:06:14
怎么样才能使计算出来的浮点数不会出现下面这种情况?
——————————————————————————————
第一组数: 1.1 1.2 1.3 1.4
第二组数: 2.1 2.2 2.3 2.4
合计: 3.2 3.40003 3.59996 3.8
——————————————————————————————
<script language="javascript" author="Http://www.TopScripts.net">
function count(num,step){
var obj,i,total=0;
for (i=((num % step==0)?step : (num % step));i<num;i+=step){
obj=eval("theForm.TextBox"+i);
total=total+parseFloat(obj.value);
}
return total;
}
function countNum(){
theForm.TextBox15.value=count(15,7)
theForm.TextBox16.value=count(16,7)
theForm.TextBox17.value=count(17,7)
theForm.TextBox18.value=count(18,7)
theForm.TextBox19.value=count(19,7)
theForm.TextBox20.value=count(20,7)
theForm.TextBox21.value=count(21,7)
}
setTimeout("countNum()",2000);
-->
</script>

<table align=center>
<form name="theForm">
<tr>
<td>第一组数:</td>
<td><input type="text" size="10" name="TextBox1" value="1.1"></td>
<td><input type="text" size="10" name="TextBox2" value="1.2"></td>
<td><input type="text" size="10" name="TextBox3" value="1.3"></td>
<td><input type="text" size="10" name="TextBox4" value="1.4"></td>
<td><input type="text" size="10" name="TextBox5" value="1.5"></td>
<td><input type="text" size="10" name="TextBox6" value="1.6"></td>
<td><input type="text" size="10" name="TextBox7" value="1.7"></td>
</tr>
<tr>
<td>第二组数:</td>
<td><input type="text" size="10" name="TextBox8" value="2.1"></td>
<td><input type="text" size="10" name="TextBox9" value="2.2" autocomplete="off"></td>
<td><input type="text" size="10" name="TextBox10" value="2.3" autocomplete="off"></td>
<td><input type="text" size="10" name="TextBox11" value="1.1"></td>
<td><input type="text" size="10" name="TextBox12" value="6.1"></td>
<td><input type="text" size="10" name="TextBox13" value="1.2"></td>
<td><input type="text" size="10" name="TextBox14" value="1.3"></td>
</tr>
<tr>
<td>合计:</td>
<td><input type="text" size="10" name="TextBox15"></td>
<td><input type="text" size="10" name="TextBox16"></td>
<td><input type="text" size="10" name="TextBox17"></td>
<td><input type="text" size="10" name="TextBox18""></td>
<td><input type="text" size="10" name="TextBox19"></td>
<td><input type="text" size="10" name="TextBox20"></td>
<td><input type="text" size="10" name="TextBox21"></td>
</tr>
</form>
</table>
...全文
66 1 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
bai85097280 2004-09-27
  • 打赏
  • 举报
回复
function count(num,step){
var obj,i,total=0,ss;
for (i=((num % step==0)?step : (num % step));i<num;i+=step){
obj=eval("theForm.TextBox"+i);
total=total+parseFloat(obj.value)
ss=total.toFixed(2);
}
return ss;
}
浮点数运算常见的问题,对其结果保留小数点后2位

87,996

社区成员

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

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