ILibNumFmt constructor

ILibNumFmt(
  1. ILibNumFmtOptions options
)

Create a formatter from options. Unspecified options fall back to the locale's defaults.

Implementation

ILibNumFmt(ILibNumFmtOptions options) {
  _locale = options.locale ?? locale_state.currentLocale;
  _type = _validType(options.type);

  final ILibLocaleInfo locInfo = ILibLocaleInfo(_locale);

  // Resolve style
  if (_type == 'currency') {
    _style = (options.style == 'common' || options.style == 'iso')
        ? options.style!
        : 'common';
  } else {
    _style = options.style ?? 'standard';
  }

  // Resolve fraction digits from options
  _maxFractionDigits = options.maxFractionDigits;
  _minFractionDigits = options.minFractionDigits;
  _significantDigits = options.significantDigits;

  // Enforce limits on significantDigits
  if (_significantDigits != null) {
    if (_significantDigits! < 1) {
      _significantDigits = 1;
    }
    if (_significantDigits! > 20) {
      _significantDigits = 20;
    }
  }
  // Enforce limits on minFractionDigits
  if (_minFractionDigits != null) {
    if (_minFractionDigits! < 0) {
      _minFractionDigits = 0;
    }
    if (_minFractionDigits! > 20) {
      _minFractionDigits = 20;
    }
  }

  // Currency setup
  if (_type == 'currency') {
    if (options.currency == null) {
      throw ArgumentError(
          'A currency property is required in the options to the number '
          'formatter constructor when the type property is set to currency.');
    }
    _initCurrency(options.currency, locInfo);
  }

  // Percentage templates
  if (_type == 'percentage') {
    _template = locInfo.getPercentageFormat();
    _templateNegative = locInfo.getNegativePercentageFormat();
  }

  // Number negative template
  if (_type == 'number') {
    _templateNegative = locInfo.getNegativeNumberFormat();
  }

  _roundingMode = options.roundingMode ?? locInfo.getRoundingMode();
  // if the mode name is not a known rounding function,
  // fall back to halfdown for both the function and the reported mode.
  final double Function(double)? round =
      math_utils.lookupRoundingFunction(_roundingMode);
  if (round != null) {
    _round = round;
  } else {
    _roundingMode = 'halfdown';
    _round = math_utils.roundHalfdown;
  }

  // Resolve useNative
  _resolveUseNative(options.useNative, locInfo);

  // Init separators, grouping, digits
  _init(locInfo);
}