javascriptroundingtofixed

How do I replace the dot with a comma and round the value to two decimals?


var calcTotalprice = function () {
    var price1 = parseFloat($('#price1').html());
    var price2 = parseFloat($('#price2').html());
    overall = (price1+price2);
    $('#total-amount').html(overall);
}

var price1 = 1.99;
var price2 = 5.47;

How to add function to change dot to comma in price number and round it to two decimal


Solution

  • You can use ".toFixed(x)" function to round your prices:

    price1 = price1.toFixed(2)
    

    And then you can use method ".toString()" to convert your value to string:

    price1 = price1.toString()
    

    Also, you can use method ".replace("..","..")" to replace "." for ",":

    price1 = price1.replace(".", ",")
    

    Result:

    price1 = price1.toFixed(2).toString().replace(".", ",")
    

    Updated answer

    .toFixed already returns a string, so doing .toString() is not needed. This is more than enough:

    price1 = price1.toFixed(2).replace(".", ",");