如何使用jQuery/Javascript将0.0099999999999909舍入到0.01?

Mic*_* LB 4 javascript jquery rounding

var figure = 0.0099999999999909;
alert(figure.toFixed(2));
Run Code Online (Sandbox Code Playgroud)

我读过这篇文章,但我仍然被困住了.

有没有办法使用jQuery/Javascript将0.0099999999999909舍入到0.01?

我在代码片段上的示例实际上有效,但它不在我的实际代码中;

// 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;
        }
    });
});
Run Code Online (Sandbox Code Playgroud)

Dav*_*ave 6

把它放在一个JS包含的地方.

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

这样称之为2之后的数字现在是你想要舍入的小数.

alert(roundNumber( 0.0099999999999909,2));
Run Code Online (Sandbox Code Playgroud)

在你的情况下,它是 alert(roundNumber(figure,2));

工作实施代码:

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;
        }
    });
});
Run Code Online (Sandbox Code Playgroud)