toNumValue function

num toNumValue(
  1. Object? data, {
  2. num? min,
  3. num? max,
})

Converts data to num or throws FormatException if cannot convert.

Returned value is either int or double that implement num.

If provided min and max are used to clamp the returned value.

Implementation

num toNumValue(Object? data, {num? min, num? max}) {
  if (data == null) throw const NullValueException();
  num result;
  if (data is num) {
    result = data;
  } else if (data is BigInt) {
    result = data.isValidInt ? data.toInt() : data.toDouble();
  } else if (data is String) {
    // first try to parse as int, otherwise as double, and if that fails throws
    result = int.tryParse(data) ?? double.parse(data);
  } else if (data is bool) {
    result = data ? 1 : 0;
  } else {
    throw ConversionException(target: num, data: data);
  }
  if (min != null && result < min) {
    result = min;
  }
  if (max != null && result > max) {
    result = max;
  }
  return result;
}