问题描述
我想用JavaScript格式化价格。
我想要一个函数,它接受一个浮点型数字为参数并返回如下字符串格式:
"$ 2,500.00"
最好的方法是什么?
解决方案
最简洁最快的方法
此解决方案兼容每个主要浏览器:
(12345.67).toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,'); // 12,345.67
我们先使用toFixed
方法确定保留几位小数,然而使用正则匹配整数部分,每3位连续的整数则匹配,并且再其后部添加,
号。
自定义方法
如果你需要在每个数字之间使用,
,则可以使用此方法:
function formatMoney(n, c, d, t) {
var c = isNaN(c = Math.abs(c)) ? 2 : c,
d = d == undefined ? "." : d,
t = t == undefined ? "," : t,
s = n < 0 ? "-" : "",
i = String(parseInt(n = Math.abs(Number(n) || 0).toFixed(c))),
j = (j = i.length) > 3 ? j % 3 : 0;
return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
};
使用举例:
(123456789.12345).formatMoney(2, ".", ",");
如果你总是要使用.
和,
,你可以省略它们:
(123456789.12345).formatMoney(2);
自定义方法(ES6)
如果您可以使用现代ECMAScript语法(即通过Babel),您可以使用这个更简单的函数:
function formatMoney(amount, decimalCount = 2, decimal = ".", thousands = ",") {
try {
decimalCount = Math.abs(decimalCount);
decimalCount = isNaN(decimalCount) ? 2 : decimalCount;
const negativeSign = amount < 0 ? "-" : "";
let i = parseInt(amount = Math.abs(Number(amount) || 0).toFixed(decimalCount)).toString();
let j = (i.length > 3) ? i.length % 3 : 0;
return negativeSign + (j ? i.substr(0, j) + thousands : '') + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + thousands) + (decimalCount ? decimal + Math.abs(amount - i).toFixed(decimalCount).slice(2) : "");
} catch (e) {
console.log(e)
}
};