toPercentage method

  1. @useResult
String toPercentage({
  1. int decimalPlaces = 0,
  2. bool doRoundDown = true,
})

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: If true (default), rounds down to the nearest value. If false, 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)}%';
}