I am using the following code snippet to calculate a total price. This works great except #totalPrice on some occasions expands out to for example $267.9999999999. How do I reformat #totalPrice within this function to just round to two decimals as is standard in dealing with price.
function getTotalCost(inventory) {
if(inventory) {
getTotalParts(inventory);
getTotalMarkup(inventory);
}
var labor = $('#labor').val() * 1;
var totals = 0;
for(i in totalMarkup) {
totals += totalMarkup[i];
}
totalCost = totals+labor;
/*if(totals == 0) {
totalCost = 0;
}*/
$('#totalPrice').html(totalCost);
}
You can have:
See:
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Number/toFixed
Notice that
toFixedmethod returns a formatted number, therefore converts the number to a string. It’s not a problem here becausehtmlwants a string, but it’s keep it in mind that in order to avoid concatenation of string when you expects sum of numbers. I believe you use$('#labor').val() * 1;for this very reason. However it’s not necessary, it’s better use method like parseFloat or the unary plus operator: