我想把1或32.23这样的字符串解析为整数和双精度数。我怎么能和达特在一起?
当前回答
每支镖2.6支
int的可选参数onError。不建议使用Parse。因此,应该使用int。tryParse代替。
注意: 这同样适用于double.parse。因此,使用double。tryParse代替。
/**
* ...
*
* The [onError] parameter is deprecated and will be removed.
* Instead of `int.parse(string, onError: (string) => ...)`,
* you should use `int.tryParse(string) ?? (...)`.
*
* ...
*/
external static int parse(String source, {int radix, @deprecated int onError(String source)});
区别在于int。如果源字符串无效,tryParse返回null。
/**
* Parse [source] as a, possibly signed, integer literal and return its value.
*
* Like [parse] except that this function returns `null` where a
* similar call to [parse] would throw a [FormatException],
* and the [source] must still not be `null`.
*/
external static int tryParse(String source, {int radix});
所以,在你的例子中,它应该是这样的:
// Valid source value
int parsedValue1 = int.tryParse('12345');
print(parsedValue1); // 12345
// Error handling
int parsedValue2 = int.tryParse('');
if (parsedValue2 == null) {
print(parsedValue2); // null
//
// handle the error here ...
//
}
其他回答
每支镖2.6支
int的可选参数onError。不建议使用Parse。因此,应该使用int。tryParse代替。
注意: 这同样适用于double.parse。因此,使用double。tryParse代替。
/**
* ...
*
* The [onError] parameter is deprecated and will be removed.
* Instead of `int.parse(string, onError: (string) => ...)`,
* you should use `int.tryParse(string) ?? (...)`.
*
* ...
*/
external static int parse(String source, {int radix, @deprecated int onError(String source)});
区别在于int。如果源字符串无效,tryParse返回null。
/**
* Parse [source] as a, possibly signed, integer literal and return its value.
*
* Like [parse] except that this function returns `null` where a
* similar call to [parse] would throw a [FormatException],
* and the [source] must still not be `null`.
*/
external static int tryParse(String source, {int radix});
所以,在你的例子中,它应该是这样的:
// Valid source value
int parsedValue1 = int.tryParse('12345');
print(parsedValue1); // 12345
// Error handling
int parsedValue2 = int.tryParse('');
if (parsedValue2 == null) {
print(parsedValue2); // null
//
// handle the error here ...
//
}
String age = stdin.readLineSync()!; // first take the input from user in string form
int.parse(age); // then parse it to integer that's it
你可以用int来解析字符串。解析('你的字符串值');
示例:- int num = int.parse('110011');打印(num);//打印110011;
如果你不知道你的类型是string还是int,你可以这样做:
int parseInt(dynamic s){
if(s.runtimeType==String) return int.parse(s);
return s as int;
}
双:
double parseDouble(dynamic s){
if(s.runtimeType==String) return double.parse(s);
return s as double;
}
因此你可以使用parseInt('1')或parseInt(1)
在Dart 2 int。tryParse可用。
对于无效输入,它返回null而不是抛出。你可以这样使用它:
int val = int.tryParse(text) ?? defaultValue;
推荐文章
- JavaScript中变量字符串的XML解析
- 我如何在c++中创建一个随机的字母数字字符串?
- 如何改变循环进度指示器的颜色
- InkWell没有显示涟漪效应
- 如何使用JavaScript大写字符串中每个单词的第一个字母?
- Node.js上的html解析器
- Java中的split()方法对点(.)不起作用。
- 我如何检查如果一个变量是JavaScript字符串?
- 如何显示有两个小数点后的浮点数?
- 在Lua中拆分字符串?
- 如何在Python中按字母顺序排序字符串中的字母
- python: SyntaxError: EOL扫描字符串文字
- PHP子字符串提取。获取第一个'/'之前的字符串或整个字符串
- 弹出时强制颤振导航器重新加载状态
- 双引号vs单引号