[英]decimal places in JS
I have two form inputs which display the calculated invoice subtotal and total of a form. 我有两个表单输入,分别显示计算出的发票小计和总计。
The problem I'm having is it's not displaying 2 decimal places. 我遇到的问题是它没有显示2个小数位。
Subtotal function 小计功能
function calcProdSubTotal() {
var prodSubTotal = 0;
$(".row-total-input").each(function(){
var valString = $(this).val() || 0;
prodSubTotal += parseInt(valString);
});
$("#product-subtotal").val(prodSubTotal);
};
Total function 总功能
function calcOrderTotal() {
var orderTotal = 0;
var productSubtotal = $("#product-subtotal").val() || 0;
var productTax = $("#product-tax").val() || 0;
var orderTotal = parseInt(productSubtotal) + parseInt(productTax);
var orderTotalNice = "$" + orderTotal;
$("#order-total").val(orderTotalNice);
};
How do i go about displaying two decimal places? 如何显示两个小数位?
You may want to look here: http://www.mredkj.com/javascript/nfbasic2.html 您可能需要在这里查看: http : //www.mredkj.com/javascript/nfbasic2.html
Basically you can use toFixed(2)
, but then you get some rounding. 基本上,您可以使用
toFixed(2)
,但是随后您需要进行四舍五入。
Or, if rounding is bad you can do parseInt(productTax * 100) / 100
. 或者,如果舍入不好,则可以执行
parseInt(productTax * 100) / 100
。
If you are working with real numbers it would be better to use parseFloat
instead of parseInt
. 如果您使用实数,最好使用
parseFloat
而不是parseInt
。 To format the number you could use the toFixed
function: 要格式化数字,可以使用
toFixed
函数:
$("#product-subtotal").val(prodSubTotal.toFixed(2));
change $("#product-subtotal").val(prodSubTotal);
更改
$("#product-subtotal").val(prodSubTotal);
to $("#product-subtotal").val(addDecimals(prodSubTotal));
到
$("#product-subtotal").val(addDecimals(prodSubTotal));
and change $("#product-subtotal").val(prodSubTotal);
并更改
$("#product-subtotal").val(prodSubTotal);
to $("#product-subtotal").val(addDecimals(prodSubTotal));
到
$("#product-subtotal").val(addDecimals(prodSubTotal));
function addDecimals(a){
a += "";
var i=a.indexOf('.');
if(i<0){
return a + ".00";
}
var j = a.substring(i);
console.log(j);
if(j.length<3){
for(var k=j.length;k<3;k++)
a+='0';
return a;
}
if(j.length>3){
return a.substring(0, i)+j.substring(0,3);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.