Dart how to add commas to a string number
You just forgot get first digits into group. Use this short one:
'12345kWh'.replaceAllMapped(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 = 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');}
It works perfectly:
0 -> 010 -> 10123 -> 1231230 -> 1,23012300 -> 12,300123040 -> 123,04012k -> 12k12 -> 12
import 'package:intl/intl.dart';var f = NumberFormat("###,###.0#", "en_US");print(f.format(int.parse("1000300")));
prints 1,000,300.0check dart's NumberFormat here
The format is specified as a pattern using a subset of the ICU formatting patterns.
- 0 A single digit
#
A single digit, omitted if the value is zero- . Decimal separator
-
Minus sign- , Grouping separator
- E Separates mantissa and expontent
+
-
Before an exponent, to say it should be prefixed with a plus sign.- % - In prefix or suffix, multiply by 100 and show as percentage
- ‰ (\u2030) In prefix or suffix, multiply by 1000 and show as per mille
- ¤ (\u00A4) Currency sign, replaced by currency name
- ' Used to quote special characters
- ; Used to separate the positive and negative patterns (if both present)