Javascript 尝试将数字格式化为 2 个小数位 jQuery
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4407450/
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
Trying to format number to 2 decimal places jQuery
提问by benhowdle89
Possible Duplicate:
JavaScript: formatting number with exactly two decimals
可能的重复:
JavaScript:用两位小数格式化数字
Getting a bit muddled up using variables and now cant seem to get calculation to work at all!?
使用变量有点混乱,现在似乎根本无法进行计算!?
$("#discount").change(function(){
var list = $("#list").val();
var discount = $("#discount").val();
var price = $("#price");
var temp = discount * list;
var temp1 = list - temp;
var total = parseFloat($(this).temp1()).toFixed(2);
price.val(total);
});
回答by Andy E
$(this).temp1()
looks particularly out of place, I think you just meant to use the temp1
variable. Since it's already a number, you don't need to use parseFloat
on it either:
$(this).temp1()
看起来特别不合适,我想你只是想使用这个temp1
变量。由于它已经是一个数字,因此您也不需要使用parseFloat
它:
$("#discount").change(function() {
var list = $("#list").val();
var discount = $("#discount").val();
var price = $("#price");
var temp = discount * list;
var temp1 = list - temp;
var total = temp1.toFixed(2);
price.val(total);
});
回答by VinayC
I would suggest you to convert strings to number first before calculation. For example,
我建议您在计算之前先将字符串转换为数字。例如,
var list = parseFloat($("#list").val());
var discount = parseFloat($("#discount").val());
var price = $("#price");
var total = list - (discount * list);
price.val(total.toFixed(2));
Also, if discount is in percentage (for example, say 25) then you have to divide by 100 i.e. list - (discount/100 * list)
此外,如果折扣是百分比(例如,说 25),那么你必须除以 100,即 list - (discount/100 * list)
BTW, refer this SO thread where people had warned against ToFixed usage: How to format a float in javascript?
顺便说一句,请参阅人们警告不要使用 ToFixed 的 SO 线程:How to format a float in javascript?