Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

2020-03-07 千位计数格式 #2

Open
fanmingfei opened this issue Mar 7, 2020 · 12 comments
Open

2020-03-07 千位计数格式 #2

fanmingfei opened this issue Mar 7, 2020 · 12 comments

Comments

@fanmingfei
Copy link
Member

/ **
 * 转换数字为千位计数格式
 * @params {Number} number - 输入数字
 * @renturn {String} 数字对应的千位格式的字符串
 */
function formatToThousands(number) {
 // ...
}
console.log(formatToThousands(123456789)) // 123,456,789

不强制要求使用正则,可以尽量使用正则实现,不太会正则的同学也可以顺便学习一下正则~
不需要考虑浏览器兼容性

@fanmingfei fanmingfei changed the title 2020-03-07 2020-03-07 千位计数格式 Mar 7, 2020
@joker1148
Copy link

function formatToThousands(number) {
    let num = number.toString()
    let reg = /(?=(\B)(\d{3})+$)/g;
    if(num.split(".").length == 1){
        let res = num.replace(reg,',')
        return res
    }else{
        let fmtNum = num.split(".")
        let big = fmtNum[0]
        let little = fmtNum[1]
        let res = big.replace(reg,',')
        return (res+"."+little)
    }
}
console.log(formatToThousands(123456789.11)) // 123,456,789.11
console.log(formatToThousands(123456789))    // 123,456,789

@IskenHuang
Copy link

function formatToThousands(number) {
    return number.toLocaleString()
}
console.log(formatToThousands(123456789)) // 123,456,789

@markmcsong
Copy link

function formatToThousands(number) {
  if (!number) return 0
  let str = number.toString()
  // 处理最前部分
  let len = str.length % 3,
    res = `${str.slice(0, len % 3)}`
  sub = str.slice(len % 3)

  // 匹配余下部分
  let reg = /[0-9]{1,3}/g,
    tmp = null
  while ((tmp = reg.exec(sub))) {
    res += "," + tmp
  }
  return len % 3 ? res : res.slice(1)
}
console.log(formatToThousands(123456789)) // 123,456,789
console.log(formatToThousands(12)) // 12

@xiaosen7
Copy link

xiaosen7 commented Mar 7, 2020

function formatTohousands(number) {

let [int, double = ''] = String(number).split('.');

double = double ? `.${double}` : '';

function reverseStr(str) {
    return str.split('').reverse().join('');
}

let reversedStr = reverseStr(int);

reversedStr = reversedStr.replace(/\d{3}/g, (num) => `${num},`);

let forwardStr = reverseStr(reversedStr);

int = /^-?,/.test(forwardStr) ? forwardStr.replace(/,/, '') : forwardStr;

return int + double;

}

@liuyingbin19222
Copy link

小数因为js机制会出现问题,哪一个大佬可以帮助解决一下

function formatToThousands(number){
    var  str = "";
    var arr = new Array();
    var tag = 1000;
    while(1){
        arr.push( number%tag );
        if(tag > number){
            break;
        }
        tag = tag * 1000;
    }
    var newArr = new Array();
    newArr.push(arr[0]);
    for(var i = 0 ; i < arr.length-1;i++){
        newArr.push( (arr[i+1]- arr[i])/(Math.pow(1000,i+1)) );
    }
    newArr = newArr.reverse();
    for(var  i = 0;i < newArr.length;i++){
        if(i == newArr.length -1 ){
            str += newArr[i] + "";
            break;
        }
        str += newArr[i] + "" + ","
    }
    return str;
}

@KobeBeyond
Copy link

function formatToThousands(number) {
let p = String(number).split('.')
let q = p[0];
var rgx = /(\d+)(\d{3})/;
while (rgx.test(q)) {
q = q.replace(rgx, '$1' + ',' + '$2');
}
return p.length > 1 ? q + '.' + p[1] : q
}
console.log(formatToThousands(123456789)); // 123,456,789
console.log(formatToThousands(12345678.123)); // 12,345,678.123
console.log(formatToThousands(12)); //12

@SunYiwen
Copy link

SunYiwen commented Mar 7, 2020

function formatToThousands(number) {
    number = number.toString();
    if(/\./.test(number)){//存在小数点的情况
        return number.replace(/\d(?=(\d{3})+\.)/g, "$&,");
    }else{//不存在小数点的情况
        return number.replace(/\d(?=(\d{3})+$)/g, "$&,");
    }
}
console.log(formatToThousands(123456789))

@fanmingfei
Copy link
Member Author

function formatToThousands(number) {
    return number.toLocaleString()
}
console.log(formatToThousands(123456789)) // 123,456,789

@IskenHuang 哈哈我的答案被你抢注了。

@fanmingfei
Copy link
Member Author

function formatToThousands(number) {
    const [int,decimal] = number.toString().split('.')
    const len = int.length

    let numberStr = ''
    for(let i = len - 1; i > -1; i--) {
        numberStr = int[i] + numberStr
        if(i !== 0 && (len - i) % 3 === 0) {
            numberStr = ',' + numberStr
        }
        
    }
    return decimal ? `${numberStr}.${decimal}` : numberStr
}

@LiZhaji
Copy link

LiZhaji commented Mar 7, 2020

function formatToThousands(number) {
  const [integer, decima] = number.toString().split('.')
  const temp = integer.split('').reverse().join('').replace(/(\d{3})(?=\d)/g, '$1,')
  const formatInt = temp.split('').reverse().join('')
  return formatInt + (decima ? '.' + decima : '')
 }

@FoSuCloud
Copy link

		function formatToThousands(num){
			num=String(num);
			var arr=num.indexOf('.')!=-1?num.split('.'):num;
			var str=""
			var len=arr.length>1?arr[0].length:arr.length;
			num=arr.length>1?arr[0]:arr
			if(len>3){
				var mid=(len%3)>0?(len%3):3;
				// 注意,map返回的是数组,所以直接使用加号会有一个逗号存在
				// 所以在第一个数的时候需要额外+,  其他时候不用
				str+=num.slice(0,mid)+num.slice(mid).match(/\d{3}/g).map((item,i) => i==0?(','+item):item)
			}else{
				str+=num
			}
			return arr.length>1?(str+'.'+arr[1]):str
		}
		var obj=formatToThousands(4762322187.64)
		console.log(obj)

@wwwx
Copy link

wwwx commented Apr 25, 2021

/**
 * 转换数字为千位计数格式
 * @params {Number} number - 输入数字
 * @renturn {String} 数字对应的千位格式的字符串
 */
function formatToThousands(number) {
    if (!Number.isInteger(number)) return false;
    var els = number.toString().split('');
    var arr = []
    for (var i = 0; i < els.length; i++) {
        arr.push(els[i])
        if ((i + 1) % 3 === 0 && i !== els.length - 1) {
            arr.push(',')
        }
    }

    return arr.join('')
}
console.log(formatToThousands(123456789)) // 123,456,789
console.log(formatToThousands(123456789.2233)) // false 

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests