使用replace实现格式x xxx,xx

时间:2019-09-04 13:50:14

标签: javascript

我正在尝试获取替换方法,以将字符串格式设置为:

  

100 000,10

如果写入的值是:

  

100j00 0,1 0

总是使用两位小数,并为每三个整数插入一个空格(数以千计)。 到目前为止,我还没有做到这一点。

const parse = (input) => {

    const numberString = input ? input.toString().replace(/[^0-9]/g, '') : '';
    return parseInt(numberString);
};

const NumberFormatFilter = () => {

    return (input) => {

        const number = parse(input);

        return isNaN(number) ? '' :
            number
                .toLocaleString()
                .replace(/\./g, ' ')
                .replace(/,/g, ' ');
    };
};

这将使我使用x xxx(1 000)格式,但是将其转换为x xxx,xx(1 000,20)格式时遇到问题

1 个答案:

答案 0 :(得分:0)

因此清理字符串以删除不是数字或逗号的任何内容。然后将其拆分并处理。基本思想如下。

function numberWithSep(x) {
  var parts = x.toString().split(",");
  //deal with the whole number format
  parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, " ");

  //deal with the decimal format (no rounding here)
  parts[1] = ((parts[1] || '') + "00").substr(0,2)

  // If you want rounding
  //parts[1] = Number('.' + (parts[1] || '0')).toFixed(2).substr(2,2)
  
  
  return parts.join(",");
}

function myFormat (str) {
  const cleaned = str.replace(/[^\d,]/g,'')
  return numberWithSep(cleaned)
}

const tests = [
  '100 j00 0,1 0',
  '1000',
  '1 0 0 0',
  '1000,01',
  '1234,569',
  '12345678901234567890,12',
]

tests.forEach( function (str) {
  console.log(myFormat(str))
})

其他选择是仅使用toLocaleString格式化数字。

function myFormat (str) {
  const cleaned = str.replace(/[^\d,]/g,'').replace(",",".")
  return Number(cleaned).toLocaleString('fr', { minimumFractionDigits: 2, maximumFractionDigits: 2 })
}

const tests = [
  '100 j00 0,1 0',
  '1000',
  '1 0 0 0',
  '1000,01',
  '1234,569',
  '12345678901234567890,12',
]

tests.forEach( function (str) {
  console.log(myFormat(str))
})