Javascript jQuery 将点替换为逗号并将其舍入

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13672106/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 12:37:58  来源:igfitidea点击:

jQuery Replace dot to comma and round it

javascript

提问by Peter

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

如何添加功能将价格数字中的点更改为逗号并将其四舍五入到两位小数

回答by VadimAlekseev

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

您可以使用“.toFixed(x)”函数来四舍五入您的价格:

price1 = price1.toFixed(2)

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

然后您可以使用方法“.toString()”将您的值转换为字符串:

price1 = price1.toString()

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

此外,您可以使用方法 ".replace("..","..")" 来替换 "." 为了 ”,”:

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:

.toFixed 已经返回一个字符串,因此不需要执行 .toString() 。这已经足够了:

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

回答by pala?н

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, ',');