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

【面经】字节跳动 笔试4:格式化数字。正则和非正则实现 #3

Open
liam61 opened this issue Mar 18, 2019 · 3 comments
Labels
面经 面经

Comments

@liam61
Copy link
Owner

liam61 commented Mar 18, 2019

格式化数字

要求:使用正则和非正则两种方式实现

评论区大神们,欢迎附上正则版~

// 法1:toLocaleString
// 浏览器提供该 api 对数字进行格式化,不过对于小数的处理使用的是四舍五入
let num = 1234567;
console.log(num.toLocaleString('en-US')); // 1,234,567
num = 12345.6785;
console.log(num.toLocaleString('en-US')); // 12,345.679

// 法2:数组操作
function format(num) {
  if (typeof num !== 'number') return num;

  const [ first, last ] = (num + '').split('.');
  const flen = first.length;
  const tmp = first.split('').reverse().reduce((res, n, i) => {
    if ((i + 1) % 3 === 0  && i !== flen - 1) res.push(n, ',');
    else res.push(n);
    return res;
  }, []).reverse().join('');

  return last ? tmp + '.' + last : tmp;
}

// 法3:递归
function format(num) {
  if (typeof num !== 'number') return num;

  const [first, last] = (num + '').split('.');

  function run(s) {
    if (s.length <= 3) return s;
    return run(s.slice(0, -3)) + ',' + s.slice(-3);
  }

  return last ? run(first) + '.' + last : run(first);
}

console.log(format(123456)); // 123,456
console.log(format(1234567)); // 1,234,567
console.log(format(12345.6785)); // 12,345.6785
console.log(format(123456.78)); // 123,456.78
@liam61 liam61 added the 面经 面经 label Mar 18, 2019
@liam61 liam61 changed the title 【面经】字节跳动 笔试2:格式化发布时间 【面经】字节跳动 笔试4:格式化数字。正则和非正则实现 Mar 21, 2019
@zhhyang
Copy link

zhhyang commented Mar 31, 2019

如果整数部分的长度是3的整数倍,计算出来的字符串首位会是 ‘’,‘’需要判断一下
console.log(format(123456)); // ,123,456

@liam61
Copy link
Owner Author

liam61 commented Mar 31, 2019

@zhhyang 感谢纠正,已改

@Z6T
Copy link

Z6T commented Jan 26, 2021

正则版:

function format(num){
    return String(num).replace(/(\d)(?=(\d{3})+(?!\d))/g,'$1,')
}

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

No branches or pull requests

3 participants