toCurrencyString method

String toCurrencyString({
  1. String? locale,
  2. String? currencyName,
  3. int? decimalDigits,
})

Formats the rational number as a localized currency string

Note: This method converts the Rational to double for formatting via the intl package. For values requiring more than ~15 significant digits, precision may be lost in display. The Rational value itself remains exact; only the formatted output is affected.

Example:

import 'package:numeric_utils/extensions/numeric_extensions.dart';
import 'package:rational/rational.dart';

final price = Rational.fromInt(1999, 100);  // i.e., Rational.parse('1999/100');
print(price.toCurrencyString(locale: 'en_US'));   // Output: $19.99
print(price.toCurrencyString(locale: 'fr_FR'));   // Output: 19,99 €
print(price.toCurrencyString(locale: 'ja_JP'));   // Output: ¥1,999
print(price.toCurrencyString(locale: 'en_US', currencyName: 'USD')); // Output: $19.99

Parameters:

  • locale: The locale to use for formatting the currency. Defaults to the system's default locale.
  • currencyName: Optional currency name (e.g., 'USD', 'EUR') to use. If not provided, uses the locale's default currency.
  • decimalDigits: Optional number of decimal digits. If not provided, uses the locale's default.

Returns: A localized currency string representation of the rational number.

Throws:

  • FormatException: If the number cannot be formatted.
  • ArgumentError: If locale is invalid.

Implementation

String toCurrencyString({
  String? locale,
  String? currencyName, // Changed from symbol to currencyName
  int? decimalDigits,
}) {
  try {
    final numberFormat = NumberFormat.simpleCurrency(
      locale: locale,
      name: currencyName, // Using currencyName here
      decimalDigits: decimalDigits,
    );

    return numberFormat.format(toDouble());
  } on FormatException catch (e) {
    throw FormatException('Failed to format currency: ${e.message}', e.source, e.offset);
  } catch (e) {
    throw ArgumentError('Invalid Locale');
  }
}