1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
function formatMoney(number, places, symbol, thousand, decimal) {
number = number || 0;
places = !isNaN(places = Math.abs(places)) ? places : 2;
symbol = symbol !== undefined ? symbol : "$";
thousand = thousand || ",";
decimal = decimal || ".";
var negative = number < 0 ? "-" : "",
i = parseInt(number = Math.abs(+number || 0).toFixed(places), 10) + "",
j = (a = i.length) > 3 ? a % 3 : 0;
return symbol + negative + (j ? i.substr(0, j) + thousand : "")
+ i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + thousand)
+ (places ? decimal
+ Math.abs(number - i).toFixed(places).slice(2) : "");
}
// 把12345.67变成美元格式,$12,345.67
console.log(formatMoney(12345.67));
// 把12345.67变成人民币格式,并保留3位小数,¥12,345.670
console.log(formatMoney(12345.67, 3, "¥"));
// 把$12,345.67变成纯数字12345.67
console.log(parseFloat('$12,345.67'.replace(/[^0-9-.]/g, '')));
Post
Cancel
JS将数字格式化成货币(钱)格式
This post is licensed under
CC BY 4.0
by the author.