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

How to round 0.0099999999999909 to 0.01 using jQuery/Javascript?

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

我读过 this 但我还是卡住了。

有没有办法使用 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;
        }
    });
});

把这个放在 JS 的某个地方。

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

这样称呼它,数字后面的 2 现在是您要四舍五入到的小数位数。

alert(roundNumber( 0.0099999999999909,2));

你的情况是 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;
        }
    });
});