dongyuanxin / blog

📚 专注Web与算法
https://0x98k.com
MIT License
1.37k stars 183 forks source link

「评论」正则表达式 #91

Open dongyuanxin opened 5 years ago

dongyuanxin commented 5 years ago

正则表达式:https://xin-tan.com/passages/2019-03-21-js-re/

zhou-z-xin commented 4 years ago
export const addSeparator = (str = '', sep = ',') => {
  str += '';
  const arr = str.split('.'),
    reg = /(?=((?!\b)\d{3})+$)/g
  let integer = arr[0],
    decimal = arr.length > 1 ? arr[0] : '';
  integer = integer.replace(reg, sep);
  return integer + decimal;
}
dongyuanxin commented 4 years ago

@zhou-xin-undefined

测试用例中 -10000.23 的输出有问题。

ordinaryA commented 4 years ago

ordinaryA commented 4 years ago

大佬

zhou-z-xin commented 4 years ago
const addSeparator = (str = '', sep = ',') => {
  str += '';
  const arr = str.split('.'),
    reg = /(?=((?!\b)\d{3})+$)/g
  let integer = arr[0],
    decimal = arr.length <= 1 ? '' : `.${arr[1]}`;
  integer = integer.replace(reg, sep);
  return integer + decimal;
}

console.log(addSeparator(-10000.23)); // -10,000.23
console.log(addSeparator(100)); // 100
console.log(addSeparator(1234, ";")); // 1;234

上面那段代码逻辑写错了,小数位的值取错了。