gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-11-01 05:29:48 26 4
gpt4 key购买 nike

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

关于javascript - 如何使用 jQuery/Javascript 将 0.0099999999999909 舍入为 0.01?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34361567/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com