tags: js
categories: js
JS数字格式转换为千分位
不使用正则表达式
var num = 123456789;
1.格式化为千分位输出 num.toLocaleString()
//"123,456,789"
2.格式化为千分位带$符号输出
num.toLocaleString("en-US",{style:"currency",currency:"USD"})
//"$123,456,789.00"
3.格式化为带¥符号输出
num.toLocaleString("zh-Hans-CN",{style:"currency",currency:"CNY"})
//"¥123,456,789.00"
使用正则表达式
// 数字转换成货币格式 封装
// number 数字
// places 小数位
// sybol 货币前缀
// thousand 货币以什么分割
// decimal 以什么跟小数分割
// formatMoney(value, 2, "¥", ",", ".")
const formatMoney = function (number, places, symbol, thousand, decimal) {
places = !isNaN(places = Math.abs(places)) ? places : 2;
symbol = symbol !== undefined ? symbol : "¥";
thousand = thousand || ",";
decimal = decimal || ".";
if(number){
var negative = number < 0 ? "-" : "",
i = parseInt(number = Math.abs(+number || 0).toFixed(places), 10) + "",
j = (j = i.length) > 3 ? j % 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) : "");
}else{
return symbol + parseFloat(0).toFixed(places)
}
}