如何在 Jquery/Javascript 中舍入 parseFloat 结果?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9930421/
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
How to round off parseFloat results in Jquery/Javascript?
提问by Davinchie_214
How would I round off a value from a textfield with a parseFloat
result in it? This application basically sums up the value of all radio buttons when clicked and displays the sum in a textbox.
我如何将文本字段中的值四舍五入并显示parseFloat
结果?该应用程序基本上总结了单击时所有单选按钮的值,并在文本框中显示总和。
The code below works perfectly if the radio button value is an integer, however if I want to have a floating point value on the radio button, the total value will have a 100.0000000679
when it should be 100
. Any tips would be very much appreciated. Thanks in advance.
如果单选按钮值是整数,则下面的代码可以完美运行,但是如果我想在单选按钮上有一个浮点值,则总值100.0000000679
应该是100
. 任何提示将不胜感激。提前致谢。
function calcscore(){
var score = 0;
$(".calc:checked").each(function(){
score+=parseFloat($(this).val(),10);
});
$("input[name=openingsum]").val(score);
}
$().ready(function(){
$(".calc").change(function(){
calcscore();
});
});
HTML Code:
HTML代码:
<input class="calc" name="v2" type="radio" onclick="ver2(this);" value="1.6666666666666666666666666666667" />Yes
<input class="calc" name="v2" type="radio" onclick="ver2(this);" value="0" />No
回答by Neysor
At first i think you provided us with a different example then expected. If you tell us something about getting 100.0000000679
and in your code is only a value of 1.6666666666666666666666666666667
there is something wrong :)
起初,我认为您为我们提供了一个与预期不同的示例。如果您告诉我们有关获取的信息,100.0000000679
并且在您的代码中只是一个值,1.6666666666666666666666666666667
则有问题:)
So I hope your problem is only to round the correct way. For that you can use .toFixed()
所以我希望你的问题只是为了正确的方法。为此,您可以使用.toFixed()
See the example on jsfiddle
HTML:
HTML:
<input class="calc" name="v1" type="radio" onclick="ver2(this);" value="1.6666666666666666666666666666667" />Yes
<input class="calc" name="v1" type="radio" onclick="ver2(this);" value="0" />No
<br>
<input class="calc" name="v2" type="radio" onclick="ver2(this);" value="1.6666666666666666666666666666667" />Yes
<input class="calc" name="v2" type="radio" onclick="ver2(this);" value="0" />No
<br>
<input class="calc" name="v3" type="radio" onclick="ver2(this);" value="1.6666666666666666666666666666667" />Yes
<input class="calc" name="v3" type="radio" onclick="ver2(this);" value="0" />No
<br>
<input type="text" name="openingsum">?
JAVASCRIPT:
爪哇脚本:
function calcscore(){
var score = 0;
$(".calc:checked").each(function(){
score+=parseFloat($(this).val(),10);
});
score = score.toFixed(2);
$("input[name=openingsum]").val(score);
}
$().ready(function(){
$(".calc").change(function(){
calcscore();
});
});?