parseFloat四舍五入 [英] parseFloat rounding
问题描述
我有自动添加输入字段的javascript函数,但添加数字如1.35 + 1.35 + 1.35给出的输出为4.050000000000001,仅作为示例。如何将总数舍入到第二个小数而不是那个长字符串?
I have javascript function that automatically adds input fields together, but adding numbers like 1.35 + 1.35 + 1.35 gives me an output of 4.050000000000001, just as an example. How can I round the total to the second decimal instead of that long string?
输入字段不仅仅有1.35的例子,所以我需要总数在小数点后永远不会超过2个点。以下是完整的工作代码:
The input fields will have more than just the 1.35 example so I need the total to never have more than 2 points after the decimal. Here is the full working code:
<html>
<head>
<script type="text/javascript">
function Calc(className){
var elements = document.getElementsByClassName(className);
var total = 0;
for(var i = 0; i < elements.length; ++i){
total += parseFloat(elements[i].value);
}
document.form0.total.value = total;
}
function addone(field) {
field.value = Number(field.value) + 1;
Calc('add');
}
</script>
</head>
<body>
<form name="form0" id="form0">
1: <input type="text" name="box1" id="box1" class="add" value="0" onKeyUp="Calc('add')" onChange="updatesum()" onClick="this.focus();this.select();" />
<input type="button" value=" + " onclick="addone(box1);">
<br />
2: <input type="text" name="box2" id="box2" class="add" value="0" onKeyUp="Calc('add')" onClick="this.focus();this.select();" />
<input type="button" value=" + " onclick="addone(box2);">
<br />
<br />
Total: <input readonly style="border:0px; font-size:14; color:red;" id="total" name="total">
<br />
</form>
</body></html>
我尝试过的一些事情应该可行,但我显然是错误地实现了它们:
Some things I have tried, which should work but I am clearly implementing them incorrectly:
for(var i = 0; i < elements.length; ++i){
total += parseFloat(elements[i].value.toString().match(/^\d+(?:\.\d{0,2})?/));
var str = total.toFixed(2);
或
for(var i = 0; i < elements.length; ++i){
total += parseFloat(elements[i].value * 100) / 100).toFixed(2)
Math.floor
也没有运气
推荐答案
使用 toFixed()
来舍入使用传统的舍入方法将num
改为2位小数。它将在4.050000000000001到4.05之间。
Use toFixed()
to round num
to 2 decimal digits using the traditional rounding method. It will round 4.050000000000001 to 4.05.
num.toFixed(2);
您可能更喜欢使用 toPrecision()
,这将删除任何结果的尾随零。
You might prefer using toPrecision()
, which will strip any resulting trailing zeros.
示例:
1.35+1.35+1.35 => 4.050000000000001
(1.35+1.35+1.35).toFixed(2) => 4.05
(1.35+1.35+1.35).toPrecision(3) => 4.05
// or...
(1.35+1.35+1.35).toFixed(4) => 4.0500
(1.35+1.35+1.35).toPrecision(4) => 4.05
这篇关于parseFloat四舍五入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!