toPercentage method
Returns this double formatted as a percentage string.
Multiplies the value by 100 and appends a '%' symbol.
decimalPlaces: Number of decimal places to include (default: 0).doRoundDown: Iftrue(default), rounds down to the nearest value. Iffalse, uses standard rounding.
Example:
0.5.toPercentage(); // '50%'
0.756.toPercentage(decimalPlaces: 1); // '75.6%' (rounded down)
0.756.toPercentage(decimalPlaces: 1, roundDown: false); // '75.6%'
0.999.toPercentage(); // '99%' (rounded down)
0.999.toPercentage(roundDown: false); // '100%'
Implementation
@useResult
String toPercentage({int decimalPlaces = 0, bool doRoundDown = true}) {
if (!doRoundDown) {
return '${(this * _percentageMultiplier).formatDouble(decimalPlaces, showTrailingZeros: false)}%';
}
// Calculate the multiplier for the specified number of decimal places
final num multiplier = pow(_base10, decimalPlaces);
// Multiply by 100 to convert to percentage and by multiplier to shift decimal
// Then use floor to round down to the nearest integer value
final double roundedValue = (this * _percentageMultiplier * multiplier).floor() / multiplier;
return '${roundedValue.formatDouble(decimalPlaces, showTrailingZeros: false)}%';
}