thousands method
Formats a number with thousands separators (commas).
Handles both integers and doubles.
Code of Practice:
1. Formatting an integer:
int largeNumber = 1234567;
String formatted = largeNumber.thousands( ) ; // '1,234,567'
2. Formatting a double:
double largeDouble = 1234567.89;
String formatted = largeDouble.thousands(); // '1,234,567.89'
Implementation
String thousands() {
try {
if (!RegExp(r'^[+-]?([\d]+|[\d]+\.[\d]+)$').hasMatch(this.toString())) {
return this.toString();
}
return this
.toString()
.replaceAllMapped(RegExp(r'\B(?=(\d{3})+(?!\d))'), (match) => ',');
} catch (e) {
return this.toString();
}
}