percentage method

String percentage({
  1. int fixed = 2,
  2. bool fit = false,
})

Converts a number into a percentage string.

The number is multiplied by 100 and a '%' sign is appended.

fixed: The number of decimal places to show. Defaults to 2. fit: If true, removes trailing '.00' from the result. Defaults to false.


Code of Practice:

  1. Default behavior:
double value = 0.8567;
String percent = value.percentage(); // '85.67%'
  1. Specifying decimal places:
double value = 0.8567;
String percent = value.percentage(fixed:  1); // '85.7%'

3. Using 'fit' to remove unnecessary decimals:

double value = 0.5;
String percent = value.percentage(fit: true); // '50%' (instead of '50.00%')

double anotherValue = 0.501; String anotherPercent = anotherValue.percentage(fit: true); // '50.10%'

Implementation

String percentage({int fixed = 2, bool fit = false}) {
  String formatted = (this * 100).toStringAsFixed(fixed);
  if (fit) {
    formatted = formatted.replaceAll(RegExp(r'\.[0]+$'), '');
  }

  return '$formatted%';
}