我需要找出dart中的字符串是否为数字。它需要在dart中的任何有效数字类型上返回true。到目前为止,我的解决方案是
bool isNumeric(String str) {
try{
var value = double.parse(str);
} on FormatException {
return false;
} finally {
return true;
}
}
是否有本地方式来做到这一点?如果没有,有没有更好的方法呢?
这可以简化一点
void main(args) {
print(isNumeric(null));
print(isNumeric(''));
print(isNumeric('x'));
print(isNumeric('123x'));
print(isNumeric('123'));
print(isNumeric('+123'));
print(isNumeric('123.456'));
print(isNumeric('1,234.567'));
print(isNumeric('1.234,567'));
print(isNumeric('-123'));
print(isNumeric('INFINITY'));
print(isNumeric(double.INFINITY.toString())); // 'Infinity'
print(isNumeric(double.NAN.toString()));
print(isNumeric('0x123'));
}
bool isNumeric(String s) {
if(s == null) {
return false;
}
return double.parse(s, (e) => null) != null;
}
false // null
false // ''
false // 'x'
false // '123x'
true // '123'
true // '+123'
true // '123.456'
false // '1,234.567'
false // '1.234,567' (would be a valid number in Austria/Germany/...)
true // '-123'
false // 'INFINITY'
true // double.INFINITY.toString()
true // double.NAN.toString()
false // '0x123'
来自double.parse DartDoc
* Examples of accepted strings:
*
* "3.14"
* " 3.14 \xA0"
* "0."
* ".0"
* "-1.e3"
* "1234E+7"
* "+.12e-9"
* "-NaN"
此版本也接受十六进制数字
bool isNumeric(String s) {
if(s == null) {
return false;
}
// TODO according to DartDoc num.parse() includes both (double.parse and int.parse)
return double.parse(s, (e) => null) != null ||
int.parse(s, onError: (e) => null) != null;
}
print(int.parse('0xab'));
真正
在Dart 2中,不推荐使用此方法
int.parse(s, onError: (e) => null)
相反,使用
bool _isNumeric(String str) {
if(str == null) {
return false;
}
return double.tryParse(str) != null;
}
更短。尽管它也适用于double
,但更准确地说使用num
。
isNumeric(string) => num.tryParse(string) != null;
num.tryParse
里面:
static num tryParse(String input) {
String source = input.trim();
return int.tryParse(source) ?? double.tryParse(source);
}