简体   繁体   中英

jQuery Replace dot to comma and round it

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

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(".", ",");

Try this:

var price1 = 1.99234;

// Format number to 2 decimal places
var num1 = price1.toFixed(2);

// Replace dot with a comma
var num2 = num1.toString().replace(/\./g, ',');

A solution to round and replace with a class selector. This code formats 10.0 to 10,00

$('.formatInteger').each(function(){
  let int = parseFloat($(this).text()).toFixed(2)
  $(this).html(int.toString().replace(".", ","))
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM