formatDouble method
Formats this double to a string with a specified number of decimal places.
Optionally removes trailing zeros after the decimal point when
showTrailingZeros is false.
Examples when showTrailingZeros is false:
-
15.00 → "15"
-
15.50 → "15.5"
-
15.05 → "15.05"
-
decimalPlaces: The number of decimal places to format to. -
showTrailingZeros: Whether to keep trailing zeros (default:true).
Example:
15.0.formatDouble(2); // '15.00'
15.0.formatDouble(2, showTrailingZeros: false); // '15'
15.5.formatDouble(2, showTrailingZeros: false); // '15.5'
15.05.formatDouble(2, showTrailingZeros: false); // '15.05'
Implementation
String formatDouble(int decimalPlaces, {bool showTrailingZeros = true}) {
if (isNaN) return 'NaN';
if (isInfinite) return isNegative ? '-∞' : '∞';
// toStringAsFixed throws RangeError for decimalPlaces < 0 or > 20
final int clampedPlaces = decimalPlaces.clamp(0, 20);
final String result = toStringAsFixed(clampedPlaces);
if (showTrailingZeros || clampedPlaces == 0) {
return result;
}
// Remove trailing zeros, then remove trailing decimal point if present
return result.replaceAll(_trailingZerosRegex, '').replaceAll(_trailingDecimalPointRegex, '');
}