parseInt function

int? parseInt(
  1. Object? v, [
  2. int? def
])

Parses v to int.

def The default value if v is invalid.

Implementation

int? parseInt(Object? v, [int? def]) {
  if (v == null) return def;

  if (v is int) return v;
  if (v is num) return v.toInt();

  if (v is DateTime) return v.millisecondsSinceEpoch;

  String s;
  if (v is String) {
    s = v;
  } else {
    s = v.toString();
  }

  s = s.trim();

  if (s.isEmpty) return def;

  num? n = int.tryParse(s);

  if (n == null) {
    var d = double.tryParse(s);
    if (d != null) {
      return d.toInt();
    }
  }

  return n as int? ?? def;
}