toDecimalString method

String toDecimalString(
  1. int decimalPlaces, {
  2. bool keepTrailingZeros = false,
})

Returns a string representation of the number with a given number of decimal places.

If keepTrailingZeros is true, trailing zeros will be kept in the result, otherwise, they will be removed.

Implementation

String toDecimalString(int decimalPlaces, {bool keepTrailingZeros = false}) {
  var formatted = this?.toStringAsFixed(decimalPlaces) ?? '';

  // If the user doesn't want to keep trailing zeros
  if (!keepTrailingZeros) {
    formatted = formatted
        .replaceAll(RegExp(r'0+$'), '')
        .replaceAll(RegExp(r'\.$'), '');
  }

  return formatted;
}