如何舍入parseFloat导致Jquery / Javascript? [英] How to round off parseFloat results in Jquery/Javascript?

查看:82
本文介绍了如何舍入parseFloat导致Jquery / Javascript?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将带有 parseFloat 结果的文本字段中的值四舍五入?此应用程序基本上总结了单击时所有单选按钮的值,并在文本框中显示总和。

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.

如果单选按钮值为整数,则下面的代码可以正常工作,但是如果我想在单选按钮上有一个浮点值,那么当它应该 100 100.0000000679 $ C>。任何提示将非常感谢。在此先感谢。

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.

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代码:

<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


推荐答案

起初我认为你为我们提供了一个与预期不同的例子。如果你告诉我们一些关于获得 100.0000000679 的信息,并且在你的代码中只有 1.6666666666666666666666666666667 的值有错误:)

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

所以我希望你的问题只是围绕正确的方式。为此你可以使用 .toFixed()

So I hope your problem is only to round the correct way. For that you can use .toFixed()

参见 jsfiddle上的示例

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();
    });
});​

这篇关于如何舍入parseFloat导致Jquery / Javascript?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆