我需要找出一个字符串在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'  
符合事实的    // '123'  
符合事实的    // '+123'
符合事实的    // '123.456'  
false   // '1,234.567'  
false   // '1.234,567' (would be a valid number in Austria/Germany/...)
符合事实的    // '-123'  
false   // 'INFINITY'  
符合事实的    // double.INFINITY.toString()
符合事实的    // 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'));

符合事实的

UPDATE

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

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

Dart相关问答推荐

如何在 Dart 中创建画布元素?

dart 中 call() 的实现是什么?

StreamBuilder 会在无状态小部件中自动关闭流吗?

结合freezed和hive

为什么使用Dart作为前端开发人员?

Flutter url_launcher 未在发布模式下启动 url

Flutter 在整个屏幕上禁用touch

Flutter:我应该在哪里调用 SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle.dark)

如何组织混合HTTP服务器+web客户端Dart元素文件?

如何从类中访问元数据注释?

如何在图像内的任意点上旋转图像?

如何更改手机屏幕上的Flutter应用程序名称显示?

Flutter: shared preferences

在小部件上显示对话框

断言失败时如何在 Dart 中打印消息?

Dart 中的构造函数和初始化列表有什么区别?

如何提高数据与二进制数据转换的 Dart 性能?

如何从 Dart 中的 forEach 循环返回?

Dart 是否支持函数式编程?

如何在 Dart 中引用另一个文件?