尝试将分隔符添加到数字(逗号&和。)

时间:2014-03-16 03:55:09

标签: javascript regex

到目前为止,我有:

var addSeparators = function (input, thousandSep, fractionSep) {
  if (!input) {
    return '';
  }
  return (input + '').replace(/(\d)(?=(\d{3})+$)/g, '$1' + thousandSep);
};

如果我致电addSeparators('1000', ',', '.');,我会回复1,000

如果我致电addSeparators('1000.0234', ',', '.');,我会回复1000.0,234,但我希望1,000.0234

2 个答案:

答案 0 :(得分:0)

  var addSeparators = function (input, thousandSep, fractionSep) {
  if (!input) {
    return '';
  }
  fraction=input.toString().split('.')[1];
  fraction=fraction?fractionSep+fraction:'';
  return parseInt(input).toString().replace(/(\d)(?=(\d{3})+$)/g,'$1'+thousandSep)+fraction;
};

答案 1 :(得分:0)

试试这个

function thousandSeparator(num) {
  return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}

thousandSeparator(1000.0234);