toCurrency method
Formats this double as currency.
Example:
double price = 1234.56;
String formatted = price.toCurrency(); // '$1,234.56'
Implementation
String toCurrency({String symbol = '\$', int decimals = 2}) {
final parts = toStringAsFixed(decimals).split('.');
final integerPart = parts[0];
final decimalPart = parts.length > 1 ? parts[1] : '';
final formattedInteger = integerPart.replaceAllMapped(
RegExp(r'(\d{1,3})(?=(\d{3})+(?!\d))'),
(Match m) => '${m[1]},',
);
return '$symbol$formattedInteger${decimalPart.isNotEmpty ? '.$decimalPart' : ''}';
}