safeParseDouble function
Safely parses a dynamic
value to a double.
This function attempts to convert the provided value
to a double.
If the value
is null
, an invalid number, or cannot be parsed,
the fallback
value is returned instead.
-
Parameters:
-
Returns: A double representation of the
value
if parsing succeeds, or thefallback
value if it fails. -
Example:
safeParseDouble('3.14'); // returns 3.14
safeParseDouble(null); // returns 0 (fallback)
safeParseDouble('abc', fallback: 1.5); // returns 1.5 (fallback)
safeParseDouble(10); // returns 10.0 (automatic conversion from int)
Implementation
double safeParseDouble(dynamic value, {double fallback = 0}) {
return double.tryParse((value ?? fallback).toString()) ?? fallback;
}