📅  最后修改于: 2023-12-03 14:47:43.728000             🧑  作者: Mango
In Dart, converting a string to a double is fairly simple using the double.parse()
method. This method takes a string as an argument and returns a double.
double double.parse(String source, [double onError(String source)])
The source
parameter is the string that needs to be converted to a double. The onError
parameter is optional and it is a callback function that is called when an error occurs during the conversion process.
void main() {
String str = '3.14';
double pi = double.parse(str);
print('The value of pi is $pi');
}
Output:
The value of pi is 3.14
If the string passed as an argument is not a valid double, an error will be thrown. So, it's always a good practice to use try-catch
when parsing a string to double.
void main() {
String str = 'hello';
try {
double number = double.parse(str);
print('The value of number is $number');
} catch (e) {
print('Cannot convert string to double: $e');
}
}
Output:
Cannot convert string to double: FormatException: Invalid double
Converting a string to double in Dart is easy and can be done using the double.parse()
method. Always remember to use try-catch
when parsing a string to double to avoid errors.