将数字四舍五入到两位小数
Round number to two decimals
我试图对总数使用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
相关文章:
- 将数字四舍五入到小数点后两位
- 将数字四舍五入到小数点后两位,以设置货币格式
- 将数字四舍五入到两位小数
- 将数字格式化为货币,两位小数
- 用于输入文本字段的Javascript验证器,仅用于两位小数
- JS Regex的最后两位数字与前两位数字匹配
- 对于大的数字,在这个本地化函数上强制使用两个小数
- 始终至少显示两位小数
- 在数值结果中仅显示两位小数
- 将解析输入值输出为两位小数
- Javascript regExp接受小数前12位和小数后两位
- 如何使输入只接受两个小数,并且最多有10位数字
- 如何在Plottable.js饼图标签中将数字精度格式化为两位小数
- inputmask带两位小数的数字
- Javascript函数返回带两位小数的数字.
- 用regex定义js,允许4后的任何两位小数,404除外
- 如何防止键盘按下小数后两位数字
- 显示带有两位小数的Eur结果
- 用两位小数格式化数值var
- 检查给定的值是正数还是小数最多两位的浮点数