Created
March 7, 2018 09:13
-
-
Save guoshuai93/65afe53069e2d0042f7e22f3132904d8 to your computer and use it in GitHub Desktop.
字符串处理相关代码段
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//---------------------------- | |
// 实现数值千分位逗号隔开 | |
// 1. 正则实现 | |
function numThoundFormat(num){ | |
var res = num.toString().replace(/\d+/, function(n){ // 先提取整数部分 | |
return n.replace(/(\d)(?=(\d{3})+$)/g,function($1){ | |
return $1+","; | |
}); | |
}); | |
return res; | |
} | |
var b= 1234687234.23148762134 ; | |
console.log( numThoundFormat(b) ); // "1,234,687,234.2314875" | |
// 2. 字符串转为数组倒序排列替换 | |
function numThoundFormat2( num ){ | |
num = num.toString().split(".");// 把整数和小数部分拆开 | |
var arr = num[0].split("").reverse();// 整数部分倒序排列 | |
var res = []; | |
for( var i = 0, len = arr.length; i < len; i++ ){ | |
if( i%3 === 0 && i !== 0 ){// 每隔三位加一个逗号 | |
res.push(','); | |
} | |
res.push( arr[i] ); | |
} | |
res.reverse();// 整数部分设为正常顺序 | |
if( num[1] ){// 如果有小数部分 | |
res = res.join("").concat( "." + num[1] ); | |
}else{ | |
res = res.join(""); | |
} | |
return res; | |
} | |
//---------------------------- |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment