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}) {
final String result = toStringAsFixed(decimalPlaces);
if (showTrailingZeros || decimalPlaces == 0) {
return result;
}
// Remove trailing zeros, then remove trailing decimal point if present
return result.replaceAll(_trailingZerosRegex, '').replaceAll(_trailingDecimalPointRegex, '');
}