如何计算不相等数字的百分比



我需要计算一些不相等数字的百分比。我使用 parseFloat 计算百分比,但它仅适用于四舍五入的数字,例如 2000 或 200,给我 20% 和 2%。我不会为2200或220工作以达到2.2%或22.2%。

$(document).on('keyup', '.js-baOfferPrice.percentage', function(e) {
    var s, target = $(e.target);
    var p = $('.js-baAppPrice').text();
    s = parseFloat(parseInt(target.val(), 10) * 100) / parseInt(p, 10);
    target.val() === "" ? target.val("") : target.val(Math.round(s).toFixed(0));
});

有人可以帮忙吗?

.toFixed(0)更改为.toFixed(1)并删除Math.round()

这一行:

target.val() === "" ? target.val("") : target.val(Math.round(s).toFixed(0));

将成为:

target.val() === "" ? target.val("") : target.val(s.toFixed(1));

参考:固定
堆栈溢出参考:数学轮次(数字) vs 数字到固定(0)

不要调用Math.round(s),因为这会删除数字的小数部分。只需使用 toFixed ,并在此处指定小数位数。它将对该数字进行舍入。

if (target.val() !== "") {
    s = parseFloat(parseInt(target.val(), 10) * 100) / parseInt(p, 10);
    target.val(s.toFixed(1));
}

最新更新