Javascript四舍五入到小数点后两位 [英] Javascript rounding to two decimal places

查看:44
本文介绍了Javascript四舍五入到小数点后两位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Round to 2 Decimal Places</title>
    <script type="text/javascript"
    src="http://ajax.microsoft.com/ajax/jQuery/jquery-1.4.2.min.js">
    </script>
    <script type="text/javascript">
        $(function() {
            $('input#txtNum').blur(function() {
                var amt = parseFloat(this.value);
                //$(this).val('$' + amt.toFixed(2));
                $(this).val((Math.round(amt*100))/100).toFixed(2);
            });

        });
    </script>
</head>
<body>
    Type a decimal number in the TextBox and hit Tab
    <br />
    <input id="txtNum" type="text" />
</body>
</html>

当我输入值为100.2569时。结果显示100.26但是当我输入56.999时显示57而不是57.00或如果我给出没有小数的值,它的显示没有小数,没有两个在小数后加两个零。

when i am entering value as 100.2569.The result shows 100.26 but when i am entering 56.999 its showing 57 instead of 57.00 or if i am giving value without decimal its showing without decimals without two appending two zeroes after decimal.

推荐答案

你'在错误的地方重新调用 toFixed

You're calling toFixed in the wrong place:

$(this).val( (Math.round(amt*100)/100).toFixed(2) );

这篇关于Javascript四舍五入到小数点后两位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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