createPrecisionFormatter function

AmountToString createPrecisionFormatter(
  1. int minDecimals,
  2. int maxDecimals,
  3. int maxPrecision,
  4. String locale,
)

Creates a AmountToString transformer with specified precision.

Creates a NumberFormat based transformer function.

def fmt = createPrecisionFormatter(0, 0, 3, 'en-us');
print(fmt(123456.789)); // → '123000'

minDecimals ans maxDecimals specifies the minimum and maximum amount of decimal places included in the output. maxPrecision defines the maximum significant digits included in the output. maxPrecision can be disabled with -1. Finally locale can be used to control the number styling and decimal separator.

Will throw ArgumentError if the following conditions are not met.

  • 0 <= minDecimals <= maxDecimals
  • maxPrecision == -1 or 1 <= maxPrecision

Implementation

AmountToString createPrecisionFormatter(
    int minDecimals, int maxDecimals, int maxPrecision, String locale) {
  if (minDecimals < 0) {
    throw ArgumentError.value(
        minDecimals, 'minDecimals', 'Expected positive value.');
  }

  if (maxDecimals < 0 || maxDecimals < minDecimals) {
    throw ArgumentError.value(maxDecimals, 'maxDecimals',
        'Expected positive value larger or equal to minDecimals.');
  }

  if (maxPrecision < -1 || maxPrecision == 0) {
    throw ArgumentError.value(maxPrecision, 'maxPrecision',
        'Expected positive non zero value or -1 (no limit).');
  }

  var fmt = NumberFormat.decimalPattern(locale)
    ..minimumFractionDigits = minDecimals
    ..maximumFractionDigits = maxDecimals
    ..significantDigits = maxPrecision
    ..significantDigitsInUse = (maxPrecision > 0);

  return (double amount) {
    return fmt.format(amount);
  };
}