我想把1或32.23这样的字符串解析为整数和双精度数。我怎么能和达特在一起?
当前回答
void main(){
var x = "4";
int number = int.parse(x);//STRING to INT
var y = "4.6";
double doubleNum = double.parse(y);//STRING to DOUBLE
var z = 55;
String myStr = z.toString();//INT to STRING
}
int.parse()和double.parse()在无法解析String时抛出错误
其他回答
你可以用int来解析字符串。解析('你的字符串值');
示例:- int num = int.parse('110011');打印(num);//打印110011;
void main(){
var x = "4";
int number = int.parse(x);//STRING to INT
var y = "4.6";
double doubleNum = double.parse(y);//STRING to DOUBLE
var z = 55;
String myStr = z.toString();//INT to STRING
}
int.parse()和double.parse()在无法解析String时抛出错误
void main(){
String myString ='111';
int data = int.parse(myString);
print(data);
}
在Dart 2 int。tryParse可用。
对于无效输入,它返回null而不是抛出。你可以这样使用它:
int val = int.tryParse(text) ?? defaultValue;
每支镖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 ...
//
}
推荐文章
- 如何删除表中特定列的第一个字符?
- 我应该如何从字符串中删除所有的前导空格?- - - - - -斯威夫特
- 将整数转换为字符串,以逗号表示千
- 将JavaScript字符串中的多个空格替换为单个空格
- printf()和puts()在C语言中的区别是什么?
- 如何从SQL Server中的字符串中剥离所有非字母字符?
- jQuery -替换字符串中某个字符的所有实例
- Base64长度计算?
- 使用split("|")按管道符号拆分Java字符串
- 如何用jQuery / JavaScript解析JSON数据?
- Std::cin输入空格?
- JavaScript中变量字符串的XML解析
- 我如何在c++中创建一个随机的字母数字字符串?
- 如何改变循环进度指示器的颜色
- InkWell没有显示涟漪效应