parsePercent function

num? parsePercent(
  1. Object? v, [
  2. double? def
])

Parses v as a percentage from 0..100.

def the default value if v is invalid.

Implementation

num? parsePercent(Object? v, [double? def]) {
  if (v == null) return null;

  if (v is num) {
    return v.isNaN || v.isInfinite ? null : v;
  }

  if (v is String) {
    var s = v.trim();
    if (s.endsWith('%')) {
      s = s.substring(0, s.length - 1).trim();
      return parseNum(s);
    } else {
      var n = num.parse(v);
      if (n >= 0 && n <= 1) {
        return n * 100;
      } else {
        return n;
      }
    }
  }

  return parseNum(v);
}