4

var figure = 0.0099999999999909;
alert(figure.toFixed(2));

I've read this but I'm still stuck.

Is there a way to round 0.0099999999999909 to 0.01 using jQuery/Javascript?

My example on the snippet actually works but it doesn't in my actual code;

// allocate button

$( "#allocate_total_amount_paid" ).click(function() {
    var totalAmountPaid = parseFloat($("#total_amount_paid").val());
    $( ".amount_received" ).each(function( index ) {
        var thisAmount = $(this).attr("max");
        if (thisAmount <= totalAmountPaid) {
            // If we have enough for this payment, pay it in full
            $(this).val(thisAmount).trigger('input');
            // and then subtract from the total payment
            totalAmountPaid -= thisAmount;
        } else {
            // We don't have enough, so just pay what we have available
            $(this).val(totalAmountPaid).trigger('input');
            // Now we have nothing left, use 0 for remaining rows
            totalAmountPaid = 0;
        }
    });
});
Community
  • 1
  • 1
Michael LB
  • 2,715
  • 4
  • 23
  • 38

1 Answers1

6

Put this in a JS include somewhere.

function roundNumber(num, dec) {
    var result = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);
    return result;
}

call it like this the 2 after the number is now many decimals you want to round to.

alert(roundNumber( 0.0099999999999909,2));

in your case it'd be alert(roundNumber(figure,2));

WORKING IMPLEMENTED CODE:

function roundNumber(num, dec) {
    var result = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);
    return result;
}

// allocate button

$( "#allocate_total_amount_paid" ).click(function() {
    var totalAmountPaid = parseFloat($("#total_amount_paid").val());
    $( ".amount_received" ).each(function( index ) {
        var thisAmount = parseFloat($(this).attr("max"));
        if (thisAmount <= totalAmountPaid) {
            // If we have enough for this payment, pay it in full
            $(this).val(roundNumber(thisAmount,2)).trigger('input');
            // and then subtract from the total payment
            totalAmountPaid -= thisAmount;
        } else {
            // We don't have enough, so just pay what we have available
            $(this).val(roundNumber(totalAmountPaid,2)).trigger('input');
            // Now we have nothing left, use 0 for remaining rows
            totalAmountPaid = 0;
        }
    });
});
Dave
  • 3,280
  • 2
  • 22
  • 40
  • 1
    Seems far more complicated than just using num.toFixed(dec) ... https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed – John Hascall Dec 18 '15 at 18:32