formatPercent function

String formatPercent(
  1. Object? percent, {
  2. int precision = 2,
  3. bool isRatio = false,
})

Formats percent as a percentage string like: 0%, 90% or 100%.

precision amount of decimal places. isRatio if true the percent parameter is in the range 0..1.

Implementation

String formatPercent(Object? percent,
    {int precision = 2, bool isRatio = false}) {
  if (percent == null) return '0%';

  var p = parseNum(percent);
  if (p == null || p == 0 || p.isNaN) return '0%';

  if (p.isInfinite) return p.isNegative ? '-∞%' : '∞%';

  if (isRatio) {
    p = p * 100;
  }

  if (precision <= 0) return '${p.toInt()}%';

  var pStr = p.toString();

  var idx = pStr.indexOf('.');

  if (idx < 0) return '${p.toInt()}%';

  var integer = pStr.substring(0, idx);
  var decimal = pStr.substring(idx + 1);

  if (decimal.isEmpty || decimal == '0') {
    return '$integer%';
  }

  if (decimal.length > precision) {
    decimal = decimal.substring(0, precision);
  }

  return '$integer.$decimal%';
}