toNum function

num? toNum(
  1. dynamic s, {
  2. dynamic allowMalformed = true,
})

Takes a value typically a String and if its numeric parsed will output a num

Implementation

num? toNum(dynamic s, {allowMalformed = true}) {
  try {
    if (s == null || s == '' || s == 'null') return null;
    if (s is num) return s;
    if (s is String) {
      var n = num.parse(s.trim());
      if (!allowMalformed) {
        s = s.toLowerCase().trim();
        if (s.startsWith('0') && s.length > 1) return null;
        if (s.startsWith('.') || s.endsWith('.')) return null;
        if (s.startsWith('+')) return null;
        if (s.contains(hasAlpha)) return null;
        return n;
      }
      return n;
    }
    return toNum(s.toString());
  } catch (e) {
    return null;
  }
}