簡述
日常開發(fā)中帅韧,經(jīng)常有數(shù)值格式化的需求,其中啃勉,最常見的場景之一忽舟,就是千分位化。
本文從講解兩種實(shí)現(xiàn)方案淮阐,僅供參考叮阅!
常規(guī)方法
function getAddStr (str, num) {
var i, tmp = "";
for (i = 0; i< num; i++) {
tmp += str;
}
return tmp;
}
function commafy (num, index, separator, rententionNum) {
if (num === '--') {return '--';}
if (!index) {index = 3;}
if (!separator) {separator = ',';}
if (!rententionNum) {rententionNum = 2;}
num = num.toFixed(rententionNum);
var _this = this;
var reg = new RegExp('(-?[0-9]+)([0-9]{' + index + '})');
if (/^.*\..*$/.test(num)) {
var pointIndex = num.lastIndexOf('.');
var intPart = num.substring(0, pointIndex);
var pointPart = num.substring(pointIndex + 1, num.length);
var pointLen = pointPart.length;
if (pointLen >= 1) {pointPart = pointPart + getAddStr("0", rententionNum - pointLen);}
intPart = intPart + '';
while(reg.test(intPart)) {
intPart = intPart.replace(reg, '$1' + separator + '$2');
}
num = intPart + '.' + pointPart;
} else {
while (reg.test(num)) {
num = num.replace(reg, '$1' + separator + '$2');
}
num = num + '.' + _this.getAddStr("0", rententionNum);
}
return num;
}
console.log(commafy(123456, 3, ',', 0)); // 123,456.00
commafy方法接收四個(gè)參數(shù) num、index泣特、 separator浩姥、 rententionNum,num為待格式化的數(shù)值状您,index格式化字符出現(xiàn)的位置(千分位格式化勒叠,默認(rèn)為3兜挨,表示每隔三位顯示一個(gè)格式化字符),separator格式化字符(默認(rèn)為“,”)眯分,rententionNum小數(shù)點(diǎn)個(gè)數(shù)(默認(rèn)為2)拌汇。除了num,其他值都是可選的颗搂。
自定義模式實(shí)現(xiàn)
function numberFormat (number, fmt) {
var fmtSplit = fmt.split('.'),
number = Number(number),
numberString = '',
min,
max;
if (isNaN(number)) return number;
// 判斷負(fù)數(shù)
if (number < 0) {
var isNegative = true;
}
// 如果有%號担猛,做百分比轉(zhuǎn)換
if (/\%/.test(fmt)) {
number *= 100;
}
// 小數(shù)部分
if (fmtSplit.length > 1) {
min = /0+/.exec(fmtSplit[1]);
max = /#+/.exec(fmtSplit[1]);
min = min == null ? 0 : min[0].length;
max = max == null ? 0 : max[0].length;
number = number.toFixed(max + min);
for(var i = 0; i< max; i++) {
if (number.slice(-1) !== '0') break;
number = number.slice(0, -1);
}
} else {
number = number.toFixed(0);
}
// 整數(shù)部分
var numberSplit = number.replace('-', '').split('.');
min = /[0]+/.exec(fmtSplit[0].replace(',',''));
min = min == null ? 0 : min[0].length;
while(numberSplit[0].length < min ) {
numberSplit[0] = '0' + numberSplit[0];
}
// 加千分位
if (fmtSplit[0].lastIndexOf(',') !== -1) {
var groupby = fmtSplit[0].slice(fmtSplit[0].lastIndexOf(','));
groupby = /[0#]+/.exec(groupby);
if (groupby != null) {
var reg = new RegExp('(-?[0-9]+)([0-9]{' + groupby[0].length + '})');
while (reg.test(numberSplit[0])){
numberSplit[0] = numberSplit[0].replace(reg, '$1,$2');
}
}
}
numberString = (isNegative ? '-' : '') + (numberSplit.length > 1 ? numberSplit.join('.') : numberSplit[0]);
return fmt.replace(/[0#\-\,\.]+/, numberString);
}
console.log(numberFormat(123456, '#,##0.00')); // 123,456.00
如上代碼,numberFormat接收兩個(gè)參數(shù)丢氢,num跟fmt傅联,num為待格式化的數(shù)值,fmt為格式化模式字符串疚察,包含#跟0兩個(gè)字符蒸走。
'#,##0.00' 表示 小數(shù)點(diǎn)后是“00”,個(gè)位是‘0’貌嫡,十位是‘#’比驻,百位是‘#’,千位是‘#’岛抄。
其中别惦,“#”表示待格式化的數(shù)值,在該位上夫椭,沒有值掸掸,則不顯示該位。又或者待格式化數(shù)值該位為0且為最高位上的數(shù)值蹭秋,也不顯示該值扰付。舉例:如果用'#,##0'格式化1000,結(jié)果為1,000仁讨;同樣的羽莺,格式化010,則結(jié)果是10(010百位的0不顯示)洞豁。
‘0’表示待格式化的數(shù)字盐固,在該位上,如果值則用0表示丈挟。'#,##0.00'格式化100時(shí)刁卜,結(jié)果是100.00。