将数字四舍五入到两位小数

Round number to two decimals

本文关键字:两位 小数 数字 四舍五入      更新时间:2023-09-26

我试图对总数使用Math.round,以仅显示两个小数,但它不能按预期工作。我做错了什么?

$(document).ready(function() {
    var totalPrice = 0;
    $('.food').click(function() {
        var $frm = $(this).parent();
        var toAdd = $frm.children(".productInput").val();
        var addPrice = parseFloat($frm.children(".priceInput").val());
        var addAmount = parseFloat($frm.children(".amountInput").val());
        if ($('.priceInput').val() == '') {
            alert('Price can not be left blank');
        };
        if ($('.amountInput').val() == '') {
            alert('Amount can not be left blank');
        } else {
            var div = $("<div>");
            div.append("<p class='amount'>" + addAmount + "</p>", "<p class='product'> " + toAdd + " </p>", "<p class='price'>" + addPrice + "</p>", "<p class='delete'>" + "X" + "</p>");
            $frm.parent().children(".messages").append(div);
            totalPrice += addAmount * addPrice;
            $(".totalPrice").text("Total Price: $" + totalPrice);
        }

        console.log(addAmount);
        console.log(addPrice);
    });

    $(document).on("click", ".delete", function() {
        /*         var subAmount = parseFloat($(this).siblings(".amount").text());
                    var subPrice = parseFloat($(this).siblings(".price").text());
                    totalPrice -= subAmount * subPrice;
                    $(".totalPrice").text("Total Price: $" + totalPrice);*/
        $(this).closest("div").remove();
        console.log(subPrice);
        console.log(subAmount);
    });
    $(document).on("mouseover", ".delete", function() {
        var hoverAmount = parseFloat($(this).siblings(".amount").text());
        var hoverPrice = parseFloat($(this).siblings(".price").text());
        totalPrice -= hoverAmount * hoverPrice;
        Math.round(totalPrice * 100) / 100
        $(".totalPrice").text("Total Price: $" + totalPrice);
        $(this).closest("div").fadeTo("fast", 0.4);
    });
    $(document).on("mouseout", ".delete", function() {
        var subAmount = parseFloat($(this).siblings(".amount").text());
        var subPrice = parseFloat($(this).siblings(".price").text());
        totalPrice += subAmount * subPrice;
        Math.round(totalPrice * 100) / 100
        $(".totalPrice").text("Total Price: $" + totalPrice);

        $(this).closest("div").fadeTo("fast", 1.0);
    })


    });

由于我使用float,数字有时会变成长小数,而不是确切的数字。我正试图通过使用Math.round来防止这种情况。如果有人对这个问题有其他解决方案,也将不胜感激。

使用Number.protype.toFixed()和2作为参数,以便将其四舍五入到两位小数
请记住,返回的值是String:

let totalPrice = 4.655555;
totalPrice = totalPrice.toFixed(2);
console.log(totalPrice);        // "4.66"
console.log(typeof totalPrice); // string

如果您想返回一个数字,请使用Number(totalPrice.toFixed(2))——请记住,即:Number((7.005).toFixed(2))将返回7(没有小数部分)

如果使用货币,最好使用不动点来提高精度。javascript中没有定点数字类型,所以可以考虑使用外部库。例如Big.js或bignumber.js