Reputation: 77
I have two form inputs which display the calculated invoice sub-total and total of a form.
The problem I'm having is it's not displaying 2 decimal places.
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?
Upvotes: 0
Views: 766
Reputation: 40507
change $("#product-subtotal").val(prodSubTotal);
to $("#product-subtotal").val(addDecimals(prodSubTotal));
and change $("#product-subtotal").val(prodSubTotal);
to $("#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);
}
}
Upvotes: 1
Reputation: 1038810
If you are working with real numbers it would be better to use parseFloat
instead of parseInt
. To format the number you could use the toFixed
function:
$("#product-subtotal").val(prodSubTotal.toFixed(2));
Upvotes: 1
Reputation: 41858
You may want to look here: http://www.mredkj.com/javascript/nfbasic2.html
Basically you can use toFixed(2)
, but then you get some rounding.
Or, if rounding is bad you can do parseInt(productTax * 100) / 100
.
Upvotes: 1