Dart how to add commas to a string number

天涯浪子 提交于 2021-01-21 00:35:13

问题


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".replaceAllMapped(new RegExp(r'/(\d)(?=(\d{3})+$)'), (match m) => "${m},"));
print("1000300".replaceAll(new RegExp(r'/\d{1,3}(?=(\d{3})+(?!\d))/g'), (match m) => "$m,"));

Is there a simpler/working way to add commas to a string number?


回答1:


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<String> 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 



回答2:


Try the following regex: (\d{1,3})(?=(\d{3})+$)

This will provide two backreferences, and replacing your number using them like $1,$2, will add commas where they are supposed to be.



来源:https://stackoverflow.com/questions/31931257/dart-how-to-add-commas-to-a-string-number

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!