toCurrency method

String toCurrency([
  1. String symbol = '\$'
])

Currency formatter.

Example:

final text = '2500.56';
final currency = text.toCurrency();
// returns: '$2,500.56'

Implementation

String toCurrency([String symbol = '\$']) {
  if (isEmpty) return this;

  symbol = symbol.normalizeCurrency;

  // remove letters and symbols except dot
  final value = replaceAll(RegExp(r'[^0-9.]'), '');
  final doubleValue = double.tryParse(value) ?? 0.0;
  final fixedValue = doubleValue.toStringAsFixed(2);
  final parts = fixedValue.split('.');

  String mathFunc(Match match) => '${match[1]},';

  final RegExp reg = RegExp(r'(\d{1,3})(?=(\d{3})+(?!\d))');
  final result = parts[0].replaceAllMapped(reg, mathFunc);

  return parts[1] == '00' ? '$symbol$result' : '$symbol$result.${parts[1]}';
}