Naomi Naomi - 6 months ago 33
Javascript Question

Math.round not working

I'm trying to use Math.round for the total to only show 2 decimals but it doesn't do that. What am I doing wrong?

$(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);
})





});


Since I'm using float, the numbers sometimes get changed into long decimals instead of the exact amount. I'm trying to prevent this by using Math.round. If anyone have another solution to the problem that would be appreciated too.

Answer

You Math.round is let alone without assignment variable such as:

totalPrice = Math.round(totalPrice * 100) / 100;
//  ^^ you're missing an assignment to store your operation result

Here's another suggestion for the two decimals:

totalPrice = Number( (totalPrice * 100) / 100).toFixed(2) );
$(".totalPrice").text("Total Price: $" + totalPrice);