toDouble static method
Converts an object to a double.
- Converts numeric types and strings that represent valid numbers to double.
- If the conversion to double fails (e.g., non-numeric string), throws a
ParsingException
.
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.
Throws a ParsingException
if the conversion fails.
Example usage:
final object1 = 5.5;
final double1 = ConvertObject.toDouble(object1); // 5.5
final object2 = '3.14';
final double2 = ConvertObject.toDouble(object2); // 3.14
final object3 = true;
final double3 = ConvertObject.toDouble(object3); // 1.0
final object4 = 'abc';
final double4 = ConvertObject.toDouble(object4); // throws ParsingException
Implementation
static double toDouble(
dynamic object, {
dynamic mapKey,
int? listIndex,
String? format,
String? locale,
}) {
if (object is double) return object;
if (mapKey != null && object is Map<dynamic, dynamic>) {
return toDouble(object[mapKey]);
}
if (listIndex != null && object is List<dynamic>) {
return toDouble(object.of(listIndex));
}
try {
if (format.isNotBlank) {
return '$object'.toDoubleFormatted(format, locale);
}
return '$object'.toDouble;
} catch (e, s) {
throw ParsingException(
error: e,
parsingInfo: 'toDouble',
stackTrace: s,
);
}
}