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

Nao*_*omi 3 javascript jquery

我试图使用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);
    })





    });
Run Code Online (Sandbox Code Playgroud)

由于我使用的是浮点数,因此数字有时会更改为长小数而不是确切的金额。我试图通过使用 Math.round 来防止这种情况。如果有人有其他解决方案来解决该问题,我们也将不胜感激。

Rok*_*jan 7

使用Number.prototype.toFixed()作为2参数,以便将其四舍五入到两位小数。
\n只要记住返回值是一个字符串:

\n

\r\n
\r\n
let totalPrice = 4.655555;\n\ntotalPrice = totalPrice.toFixed(2);\nconsole.log(totalPrice);        // "4.66"\nconsole.log(typeof totalPrice); // string
Run Code Online (Sandbox Code Playgroud)\r\n
\r\n
\r\n

\n

如果你想返回一个数字,请使用Number(totalPrice.toFixed(2))\xe2\x80\x94 只需记住 ie:Number((7.005).toFixed(2))将返回7(不带小数部分)

\n