toNum static method

num toNum(
  1. dynamic object, {
  2. dynamic mapKey,
  3. int? listIndex,
  4. String? format,
  5. String? locale,
})

Converts an object to a num.

  • Converts numeric types and strings that represent valid numbers to num.
  • If the object is null, throws a ParsingException with a nullObject error.
  • If the conversion to num fails, throws a ParsingException.

object The object to be converted to a num. mapKey (Optional) Specifies the key to extract values from a Map object. listIndex (Optional) Specifies the index to extract elements from a List object.

Returns a num if conversion is successful. Throws a ParsingException if the conversion fails or the object is null.

Example usage:

final object1 = 10;
final num1 = ConvertObject.toNum(object1); // 10

final object2 = '5.5';
final num2 = ConvertObject.toNum(object2); // 5.5

final object3 = true;
final num3 = ConvertObject.toNum(object3); // 1

final object4 = 'abc';
final num4 = ConvertObject.toNum(object4); // throws ParsingException

final object5 = null;
final num5 = ConvertObject.toNum(object5); // throws ParsingException

Implementation

static num toNum(
  dynamic object, {
  dynamic mapKey,
  int? listIndex,
  String? format,
  String? locale,
}) {
  if (object == null) {
    throw ParsingException.nullObject(
      parsingInfo: 'toNum',
      stackTrace: StackTrace.current,
    );
  }
  if (object is num) return object;
  if (mapKey != null && object is Map<dynamic, dynamic>) {
    return toNum(object[mapKey]);
  }
  if (listIndex != null && object is List<dynamic>) {
    return toNum(object.of(listIndex));
  }
  try {
    if (format.isNotBlank) return '$object'.toNumFormatted(format, locale);
    return '$object'.toNum;
  } catch (e, s) {
    throw ParsingException(
      error: e,
      parsingInfo: 'toNum',
      stackTrace: s,
    );
  }
}