Naomi
Naomi

Reputation: 1298

Round number to two decimals

I'm trying to use Math.round for the total to show only two decimals, but it doesn't work as intended. 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.

Upvotes: 3

Views: 10393

Answers (2)

Roko C. Buljan
Roko C. Buljan

Reputation: 206689

Use Number.prototype.toFixed() with 2 as argument, in order to round it to two decimals.
Just, remember that the returned value is a String:

let totalPrice = 4.655555;

totalPrice = totalPrice.toFixed(2);
console.log(totalPrice);        // "4.66"
console.log(typeof totalPrice); // string

If you want to return a number, use Number(totalPrice.toFixed(2)) — just keep in mind that i.e: Number((7.005).toFixed(2)) will return 7 (without the decimal part)

Upvotes: 7

Yuriy Yakym
Yuriy Yakym

Reputation: 3931

If you work with currency it is better to use fixed point numbers for precision. There is no fixed-point number type in javascript, so consider using external libraries. E.g. Big.js or bignumber.js

Upvotes: 0

Related Questions