将数字四舍五入保留两位小数。

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





    });

因为我正在使用浮点数,有时数字会变成长小数而不是精确的数字。我试图通过使用Math.round来避免这个问题。如果有其他解决方案,将不胜感激。


2
我认为你应该使用变量来存储 Math.round(totalPrice * 100) / 100 的结果。例如:var result = Math.round(totalPrice * 100) / 100; $(".totalPrice").text("Total Price: $" + result); - Ismail Altunören
1
totalPrice.toFixed(2) 可以将 totalPrice 的值保留两位小数。 - Jonathan Lonowski
2个回答

7

使用 Number.prototype.toFixed() 并将其参数设置为 2,以便将其舍入到小数点后两位。
只需记住返回的值是一个字符串:

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(没有小数部分)


0
如果你在处理货币方面,最好使用定点数以获得更高的精度。由于JavaScript中没有定点数类型,因此建议考虑使用外部库。例如Big.jsbignumber.js

谢谢,当我更熟悉 JavaScript 的时候,我一定会去学习这个东西的,毕竟我还是一个初学者 :) - Naomi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接