59

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

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

有没有本地方法可以做到这一点?如果没有,有没有更好的方法来做到这一点?

4

5 回答 5

88

这可以简化一点

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

真的

更新

由于{onError(String source)}现在已弃用,您可以使用tryParse

bool isNumeric(String s) {
 if (s == null) {
   return false;
 }
 return double.tryParse(s) != null;
}
于 2014-06-06T15:27:10.727 回答
49

在 Dart 2 中,此方法已被弃用

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

相反,使用

 bool _isNumeric(String str) {
    if(str == null) {
      return false;
    }
    return double.tryParse(str) != null;
  }
于 2018-09-12T15:01:54.290 回答
17

甚至更短。尽管它也可以使用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);
}
于 2019-04-10T06:20:53.533 回答
14

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

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

/// check if the string contains only numbers
 bool isNumeric(String str) {
return _numeric.hasMatch(str);
}
于 2020-05-18T21:39:12.060 回答
4
if (int.tryParse(value) == null) {
  return 'Only Number are allowed';
}
于 2021-06-16T08:41:28.713 回答