检查dart中字符串是否为数字

时间:2014-06-06 15:21:05

标签: string numbers dart isnumeric

我需要找出dart中的字符串是否为数字。它需要在dart中的任何有效数字类型上返回true。到目前为止,我的解决方案是

bool isNumeric(String str) {
  try{
    var value = double.parse(str);
  } on FormatException {
    return false;
  } finally {
    return true;
  }
}

有原生方式吗?如果没有,有没有更好的方法呢?

5 个答案:

答案 0 :(得分:18)

这可以简化一点

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'));

true

答案 1 :(得分:14)

在Dart 2中,此方法已弃用

int.parse(s, onError: (e) => null)

相反,使用

 bool _isNumeric(String str) {
    if(str == null) {
      return false;
    }
    return double.tryParse(str) != null;
  }

答案 2 :(得分:6)

任何想要使用正则表达式的非本地方式的人

RegExp _numeric = RegExp(r'^-?[0-9]+$');

/// check if the string contains only numbers
 bool isNumeric(String str) {
return _numeric.hasMatch(str);
}

答案 3 :(得分:1)

更短。尽管事实上它也可以与python test3.py ('First group : ', '1123') ('Second group : ', '45') ('Third group : ', '35') ('Third group : ', '99') 一起使用,但使用double更准确。

num

isNumeric(string) => num.tryParse(string) != null; 里面:

num.tryParse

答案 4 :(得分:0)

if (int.tryParse(value) == null) {
  return 'Only Number are allowed';
}
相关问题