jQuery 限制为 2 位小数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3020273/
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-26 14:43:38  来源:igfitidea点击:

jQuery limit to 2 decimal places

jquery

提问by Michael Pasqualone

Possible Duplicate:
JavaScript: formatting number with exactly two decimals

可能的重复:
JavaScript:用两位小数格式化数字

How do I limit the following jQuery return to 2 decimal places?

如何将以下 jQuery 返回值限制为 2 个小数位?

$("#diskamountUnit").val('$' + $("#disk").slider("value") * 1.60);

I figure I've got to throw toFixed(2) somewhere into there, but I can't seem to get the ordering right or something.

我想我必须将 toFixed(2) 扔到某个地方,但我似乎无法正确排序或其他什么。

回答by CMS

You could use a variable to make the calculation and use toFixedwhen you set the #diskamountUnitelement value:

您可以使用变量进行计算并toFixed在设置#diskamountUnit元素值时使用:

var amount = $("#disk").slider("value") * 1.60;
$("#diskamountUnit").val('$' + amount.toFixed(2));

You can also do that in one step, in the valmethod call but IMO the first way is more readable:

您也可以一步完成,在val方法调用中,但 IMO 第一种方式更具可读性:

$("#diskamountUnit").val('$' + ($("#disk").slider("value") * 1.60).toFixed(2));

回答by Rob Vanders

Here is a working example in both Javascript and jQuery:

这是 Javascript 和 jQuery 中的一个工作示例:

http://jsfiddle.net/GuLYN/312/

http://jsfiddle.net/GuLYN/312/

//In jQuery
$("#calculate").click(function() {
    var num = parseFloat($("#textbox").val());
    var new_num = $("#textbox").val(num.toFixed(2));
});


// In javascript
document.getElementById('calculate').onclick = function() {
    var num = parseFloat(document.getElementById('textbox').value);
    var new_num = num.toFixed(2);
    document.getElementById('textbox').value = new_num;
};
?