Javascript parseFloat 舍入

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4640404/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 13:24:09  来源:igfitidea点击:

parseFloat rounding

javascriptmathparsefloat

提问by JB.

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?

我有自动将输入字段添加在一起的 javascript 函数,但是添加像 1.35 + 1.35 + 1.35 这样的数字会给我 4.050000000000001 的输出,仅作为示例。如何将总数四舍五入到第二个小数而不是那个长字符串?

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:

输入字段将不仅仅是 1.35 示例,因此我需要总数在小数点后永远不会超过 2 点。这是完整的工作代码:

<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);

or

或者

for(var i = 0; i < elements.length; ++i){
total += parseFloat(elements[i].value * 100) / 100).toFixed(2)

Have also had no luck with Math.floor

也没有运气 Math.floor

回答by moinudin

Use toFixed()to round numto 2 decimal digits using the traditional rounding method. It will round 4.050000000000001 to 4.05.

使用toFixed()以圆形num为2个十进制数字采用传统的舍入方法。它会将 4.050000000000001 舍入到 4.05。

num.toFixed(2);

You might prefer using toPrecision(), which will strip any resulting trailing zeros.

您可能更喜欢使用toPrecision(),这将去除任何结果的尾随零。

Example:

示例

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

Reference: JavaScript Number Format - Decimal Precision

参考:JavaScript 数字格式 - 十进制精度

回答by JB.

var num = 4.050000000000001;

num = num.toFixed(2);

toFixedwill round up depending on how many digits after the decimal you're looking for.

toFixed将根据您要查找的小数点后的位数进行四舍五入。

回答by JB.

You can use Math.round(total*100000000000)/100000000000;in the code. It will work for most of the cases

您可以Math.round(total*100000000000)/100000000000;在代码中使用。它适用于大多数情况

回答by Real Melancon

This works:

这有效:

$(document).ready(
    function() {
            $('#field1').blur(function(){ $('#field2').val(parseFloat($(this).val() * 2.2).toFixed(1)); });
            $('#field2').blur(function(){ $('#field1').val(parseFloat($(this).val() / 2.2).toFixed(1)); });
    }
);

This fails:

这失败了:

$(document).ready(
    function() {
            $('#field1').blur(function(){ $('#field2').val(parseFloat($(this).val() * 2.2)).toFixed(1); });
            $('#field2').blur(function(){ $('#field1').val(parseFloat($(this).val() / 2.2)).toFixed(1); });
    }
);

So be careful the way you place your parenthesis ()... In first case, the rounding will work, but won't work in the second one...

所以要小心你放置括号 () 的方式......在第一种情况下,四舍五入会起作用,但在第二种情况下不起作用......

回答by Michael Borgwardt

Instead of rounding, you may want to use the port of Java's BigDecimalto get actually precise decimal math.

您可能希望使用Java 的 BigDecimal端口而不是四舍五入来获得实际精确的十进制数学。