formatCurrency function

String formatCurrency(
  1. num value, {
  2. String currency = 'USD',
  3. String? locale,
  4. int? decimalDigits,
})

Formats a currency amount with currency code or symbol and locale positioning in pure Dart.

Maps common ISO 4217 currency codes (USD, EUR, GBP, JPY, CAD, AUD, CHF, CNY, INR, BRL, KRW, RUB) to symbols, applies zero decimal places for zero-fraction currencies (JPY, KRW), and places symbols before or after the number according to locale conventions.

When locale is omitted, defaults to the active BloomI18n.instance.locale value.

formatCurrency(49.99, currency: 'USD', locale: 'en-US'); // "$49.99"
formatCurrency(49.99, currency: 'EUR', locale: 'fr-FR'); // "49,99 €"
formatCurrency(1500, currency: 'JPY', locale: 'ja-JP');   // "¥1,500"

See also:

Implementation

String formatCurrency(
  num value, {
  String currency = 'USD',
  String? locale,
  int? decimalDigits,
}) {
  final loc = (locale ?? BloomI18n.instance.locale.value).replaceAll('_', '-').toLowerCase();
  final lang = loc.split('-').first;

  final symbols = <String, String>{
    'USD': r'$',
    'EUR': '€',
    'GBP': '£',
    'JPY': '¥',
    'CAD': r'CA$',
    'AUD': r'A$',
    'CHF': 'CHF',
    'CNY': '¥',
    'INR': '₹',
    'BRL': r'R$',
    'KRW': '₩',
    'RUB': '₽',
  };

  final symbol = symbols[currency.toUpperCase()] ?? currency;
  final decimals = decimalDigits ?? (['JPY', 'KRW'].contains(currency.toUpperCase()) ? 0 : 2);
  final numStr = formatNumber(value, locale: locale, decimalDigits: decimals);

  // Position symbol
  if (['fr', 'de', 'ru', 'es', 'pt', 'it', 'sv', 'pl', 'nl', 'fi', 'no'].contains(lang)) {
    return '$numStr $symbol';
  } else if (['ar'].contains(lang)) {
    return '$symbol $numStr';
  }
  return '$symbol$numStr';
}