James Wilson James Wilson - 4 months ago 12
jQuery Question

Need to get this number down to two decimal places

I'm using parseFloat but it is still returning a number like 10.34345543454346356

Any idea what I'm missing to turn this into a whole dollar amount with two decimal places?

else
{
// Switch to Monthly
$(this).val("monthly");
$('.pts-right').removeClass('pts-switch-active');
$('.pts-left').addClass('pts-switch-active');

// Switch Pricing Box to monthly
var retailAmt = parseFloat(546.86);
var taxAmt = parseFloat(6.75 / 100); // convert to decimal
var interestRate = parseFloat(3.76 / 100); // convert to decimal
var term = parseFloat(60);

$('.pricing > div:not(.clearfix, #accordion) .pricing-price > span').each(function () {
// Grabs the three span pricing boxes
debugger;
var retail = parseFloat($(this).text().replace('$', ''));
var monthlyPayment = (parseFloat(retail) + (parseFloat(retail) * parseFloat(taxAmt)) + (parseFloat(retail) * parseFloat(interestRate))) / parseFloat(term);

$(this).text("$" + monthlyPayment);
});

}

Answer

Do as Marc B says: don't use floats to store the actual values. Keep values as integers and display them using formatting/calculation applied to the integer

Relevant: How to deal with floating point number precision in JavaScript?

// floats are bad
var payment = 540.11 + 0.2
var paymentString = '$' + payment
console.log(paymentString)
// => 540.3100000000001 

// integers are good
var payment = 54011 + 20
var paymentString = '$' + payment / 100
console.log(paymentString)
// => $540.31

If you have to deal with fractions of pennies, you can use Number.prototype.toFixed to round it

// rounding is OK for fractions of pennies

var payments = 54011 + 56392 + 52250
// 162653

var averagePayment = payments / 3
// 542.17666666666664

var paymentString = '$' + (averagePayment / 100).toFixed(2)
console.log(paymentString)
// => $ 542.18

Comments