gpt4 book ai didi

javascript - 四舍五入到两位小数

转载 作者:行者123 更新时间:2023-11-30 11:58:30 30 4
gpt4 key购买 nike

我正在尝试使用 Math.roundtotal 只显示两位小数,但它没有按预期工作。我做错了什么?

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

关于javascript - 四舍五入到两位小数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37242234/

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