我想用JavaScript格式化一个价格。
我想要一个函数,它将一个float
参数作为参数并返回string
格式如下所示:
"$ 2,500.00"
什么是最好的方法来做到这一点?
发布于 2018-03-14 16:46:17
可以使用:
var profits=2489.8237
profits.toFixed(3) //returns 2489.824 (round up)
profits.toFixed(2) //returns 2489.82
profits.toFixed(7) //returns 2489.8237000 (padding)
然后,可以添加‘$’的符号。
如果你需要“,”你可以使用:
Number.prototype.formatMoney = function(c, d, t){
var n = this,
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);
发布于 2018-03-14 17:25:08
n.toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, '$1,');
n.toFixed(2).replace(/./g, function(c, i, a) {
return i && c !== "." && ((a.length - i) % 3 === 0) ? ',' + c : c;
});
测试:
1 --> "1.00"
12 --> "12.00"
123 --> "123.00"
1234 --> "1,234.00"
12345 --> "12,345.00"
123456 --> "123,456.00"
1234567 --> "1,234,567.00"
12345.67 --> "12,345.67"
https://stackoverflow.com/questions/-100005259
复制相似问题