Dart how to add commas to a string number

前端 未结 2 1396
一整个雨季
一整个雨季 2021-02-13 02:54

I\'m trying to adapt this: Insert commas into number string to work in dart, but no luck.

either one of these don\'t work:

print(\"1000200\".replaceAllMa         


        
2条回答
  •  死守一世寂寞
    2021-02-13 03:53

    You just forgot get first digits into group. Use this short one:

    '12345kWh'.replaceAllMapped(new RegExp(r'(\d{1,3})(?=(\d{3})+(?!\d))'), (Match m) => '${m[1]},')
    

    Look at the readable version. In last part of expression I added checking to any not digit char including string end so you can use it with '12 Watt' too.

    RegExp reg = new RegExp(r'(\d{1,3})(?=(\d{3})+(?!\d))');
    Function mathFunc = (Match match) => '${match[1]},';
    
    List tests = [
      '0',
      '10',
      '123',
      '1230',
      '12300',
      '123040',
      '12k',
      '12 ',
    ];
    
    tests.forEach((String test) {
      String result = test.replaceAllMapped(reg, mathFunc);
      print('$test -> $result');
    });
    

    It works perfectly:

    0 -> 0
    10 -> 10
    123 -> 123
    1230 -> 1,230
    12300 -> 12,300
    123040 -> 123,040
    12k -> 12k
    12  -> 12 
    

提交回复
热议问题