cakecakecake February 2016

JQuery not showing correct decimal output

My problem with this is, everything is fine up to two decimal places when its preceded 1-9, however if the number is a 10th, then my script will only show to one decimal place.

E.g 200.19, 5000.42, 12.98 << will be fine however if the output should be 123.10 it will display 123.1

Here's my code:

jQuery(document).ready(function() {
  function ReplaceNumberWithCommas(yourNumber) {
    //Seperates the components of the number
    var n= yourNumber.toString().split(".");
    //Comma-fies the first part
    n[0] = n[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    //Combines the two sections
    return n.join(".");
  }

  function loanCalc() {
    //Get the parameter from the form
    var rate=jQuery('#start_rate').val();
    var priceValue=jQuery('#input_1_2').val();
    console.log("price value before"+priceValue);

    if(priceValue.indexOf('£') == 0) {
      var strEnd=jQuery('#input_1_2').val().indexOf(',') - 1;
      priceValue=parseInt(priceValue.substr(1,priceValue.strEnd))*1000;
    }else{
      priceValue=priceValue;
    }

    var princ = parseInt(priceValue);
    var term  = parseInt(jQuery('#input_1_3').val());

    var intr   = rate / 1200;
    console.log("price"+priceValue+" term"+term+" rate"+rate);
    var calculation = princ * intr / (1 - (Math.pow(1/(1 + intr), term)));

    console.log("paymenet"+calculation);

    var rePayment= calculation*term;
    var costOfCredit=princ-rePayment;
    //set the value

    jQuery('#figure').html('£'+ ReplaceNumberWithCommas(calculation.toFixed(2)));
    jQuery('#rate').html(rate+"%");

    jQuery('#total').html('£' + 
        ReplaceNumberWithCommas(rePayment.toFixed(2)));  

    jQuery('#credit').html('£' + ReplaceNumberWithCommas(
        Math.abs(costOfCredit.toFixed(2    ))));

As you can probably guess, there are 3 fields that I am displaying, the calculation, which is a percentage, 'rePayment' and 'costOfCredit'. The weird thing is 'rePayment' wor

Answers


Barmar February 2016

When you call Math.abs(), it's converting the string with 2 digits after the decimal back to a number, which loses the trailing zeroes. You should call Math.abs() first, then call toFixed() on this to add the trailing zeroes.

jQuery('#credit').html('£' +
    ReplaceNumberWithCommas(Math.abs(costOfCredit).toFixed(2)));

Post Status

Asked in February 2016
Viewed 1,692 times
Voted 13
Answered 1 times

Search




Leave an answer