正则法:
function thousandBitSeparator(num) { return num && (num .toString().indexOf('.') != -1 ? num.toString().replace(/(\d)(?=(\d{3})+\.)/g, function($0, $1) { return $1 + ","; }) : num.toString().replace(/(\d)(?=(\d{3}))/g, function($0, $1) { return $1 + ","; }));}console.log(thousandBitSeparator(1000));//1,000
自己写的:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<canvas height="600" width="800" id="canvas"/>
</body>
<script>
function tbd(num){
var arr=[];
var arrf=[];
var x=num.toString().split('');
var y=x.reverse();
console.log(x);
if(x.length>3){
for(var i=0;i<y.length;i+=3){
if(y[i+2]){
arr.push(y[i]+y[i+1]+y[i+2]);
}else if(y[i+1]){
arr.push(y[i]+y[i+1]);
}else{
arr.push(y[i]);
}
}
for(var m=0;m<arr.length;m++){
arrf.push(arr[m].split('').reverse().join(''));
}
return arrf.reverse().join(',');
}
return num;
}
console.log(tbd(1000000));
</script>
</html>