0

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);
    });

}
James Wilson
  • 5,074
  • 16
  • 63
  • 122
  • don't use floats to store currency values. you will get corrupted values. store everything as pennies as an integer. – Marc B Jul 27 '16 at 21:28
  • maybe something like this https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed? – Brodie Jul 27 '16 at 21:29
  • @MarcB out of curiosity, why will the values get corrupted? – Adjit Jul 27 '16 at 21:31

1 Answers1

2

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
Community
  • 1
  • 1
Mulan
  • 129,518
  • 31
  • 228
  • 259
  • Divisions don't return floats ? Shouldn't you instead transform into a string and then add the decimal separator ? – Lilymonade Jul 27 '16 at 21:43
  • Division doesn't only return integers, if that's what you were thinking `0/3 //=> 0.3333333333333333`. And no, you shouldn't manually add the decimal point. Use `Number.prototype.toFixed` for rounding. – Mulan Jul 27 '16 at 21:49
  • Thank you, was able to get it to work from this answer. – James Wilson Jul 27 '16 at 22:07