tryToDouble function

double? tryToDouble(
  1. dynamic object, {
  2. Object? mapKey,
  3. int? listIndex,
})

Attempts to convert an object to a double, or returns null if the object is null or conversion fails. mirroring the same static method in the ConvertObject, providing alternative easy less code usage options.

  • Converts numeric types and strings that represent valid numbers to double.
  • If the conversion to double fails (e.g., non-numeric string), logs an error and returns null.

object The object to be converted to a double. 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 double if conversion is successful, otherwise null.

Example usage:

final object1 = 5.5;
final double1 = tryToDouble(object1); // 5.5

final object2 = '3.14';
final double2 = tryToDouble(object2); // 3.14

final object3 = true;
final double3 = tryToDouble(object3); // 1.0

final object4 = 'abc';
final double4 = tryToDouble(object4); // null

final object5 = null;
final double5 = tryToDouble(object5); // null

Implementation

double? tryToDouble(
  dynamic object, {
  Object? mapKey,
  int? listIndex,
}) =>
    ConvertObject.tryToDouble(object, mapKey: mapKey, listIndex: listIndex);