formatCurrency method

String formatCurrency({
  1. String symbol = '',
  2. String locale = 'en',
  3. bool useShortFormat = false,
})

Implementation

String formatCurrency({
  String symbol = '',
  String locale = 'en',
  bool useShortFormat = false,
}) {
  if (useShortFormat) {
    if (this >= 1000000000) {
      final value = this / 1000000000;
      return '''${symbol.isEmpty ? '' : '$symbol '}${value.toStringAsFixed(value.truncateToDouble() == value ? 0 : 1)}B''';
    }
    if (this >= 1000000) {
      final value = this / 1000000;
      return '''${symbol.isEmpty ? '' : '$symbol '}${value.toStringAsFixed(value.truncateToDouble() == value ? 0 : 1)}M''';
    }
    if (this >= 1000) {
      final value = this / 1000;
      return '''${symbol.isEmpty ? '' : '$symbol '}${value.toStringAsFixed(value.truncateToDouble() == value ? 0 : 1)}K''';
    }
  }

  // For RTL languages like Arabic, the number formatting
  // will be handled correctly while still maintaining the currency
  // symbol position based on UI text direction
  final rtlLocales = ['ar', 'fa', 'he'];
  final isRtl = rtlLocales.contains(locale);

  if (isRtl) {
    final parts = toString().split('.');
    if (parts.length == 2) {
      return symbol.isEmpty
          ? '${parts[1]}.${parts[0]}'
          : '$symbol ${parts[1]}.${parts[0]}';
    } else {
      return symbol.isEmpty ? toString() : '$symbol $this';
    }
  } else {
    final formatter = NumberFormat.decimalPattern(locale);
    final formattedNumber = formatter.format(this);
    return symbol.isEmpty ? formattedNumber : '$symbol $formattedNumber';
  }
}