Dart 如何在字符串数字中添加逗号

Dart how to add commas to a string number

我正在尝试对此进行调整: Insert commas into number string 在 dart 工作,但运气不好。

其中一个不起作用:

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,"));

有没有 simpler/working 方法可以在字符串数字中添加逗号?

试试下面的正则表达式:(\d{1,3})(?=(\d{3})+$)

这将提供两个反向引用,并且像 ,, 一样使用它们替换您的号码将在它们应该出现的位置添加逗号。

您只是忘记了将第一个数字放入组中。使用这个简短的:

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

查看可读版本。在表达式的最后一部分,我添加了对包括字符串结尾在内的任何非数字字符的检查,因此您也可以将它与“12 Watt”一起使用。

RegExp reg = RegExp(r'(\d{1,3})(?=(\d{3})+(?!\d))');
String Function(Match) mathFunc = (Match match) => '${match[1]},';

List<String> tests = [
  '0',
  '10',
  '123',
  '1230',
  '12300',
  '123040',
  '12k',
  '12 ',
];

for (String test in tests) {    
  String result = test.replaceAllMapped(reg, mathFunc);
  print('$test -> $result');
}

完美运行:

0 -> 0
10 -> 10
123 -> 123
1230 -> 1,230
12300 -> 12,300
123040 -> 123,040
12k -> 12k
12  -> 12 
import 'package:intl/intl.dart';

var f = NumberFormat("###,###.0#", "en_US");
print(f.format(int.parse("1000300")));

打印 1,000,300.0 检查飞镖的 NumberFormat here

格式指定为使用 ICU 格式化模式子集的模式。

  • 0个数字
  • #单个数字,如果值为零则省略
  • 。小数分隔符
  • - 减号
  • ,分组分隔符
  • E 分隔尾数和指数
  • + - 指数前要加前缀
  • % - 在前缀或后缀中,乘以 100 并显示为百分比
  • ‰ (\u2030) 在前缀或后缀中乘以1000并按千分表显示
  • ¤ (\u00A4) 货币符号,替换为货币名称
  • ' 用于引用特殊字符
  • ;用于分隔正面和负面模式(如果两者都存在)

让我们以金额12000为例。现在我们的预期数量应该是 12,000.00

所以,解决方案是

double rawAmount = 12000;
String amount = rawAmount.toStringAsFixed(2).replaceAllMapped(RegExp(r'(\d{1,3})(?=(\d{3})+(?!\d))'), (Match m) => '${m[1]},');

或者如果您不想添加 .00 那么我们只需要使用 toString() 而不是 toStringAsFixed().

String amount = rawAmount.toString().replaceAllMapped(RegExp(r'(\d{1,3})(?=(\d{3})+(?!\d))'), (Match m) => '${m[1]},');