I would like to parse strings like "1" or "32.23" into integers and doubles. How can I do this with Dart?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
You can parse a string into an integer with int.parse()
. For example:
var myInt = int.parse('12345');
assert(myInt is int);
print(myInt); // 12345
Note that int.parse()
accepts 0x
prefixed strings. Otherwise the input is treated as base-10.
You can parse a string into a double with double.parse()
. For example:
var myDouble = double.parse('123.45');
assert(myDouble is double);
print(myDouble); // 123.45
parse()
will throw FormatException if it cannot parse the input.
回答2:
In Dart 2 int.tryParse is available.
It returns null for invalid inputs instead of throwing. You can use it like this:
int val = int.tryParse(text) ?? defaultValue;