在dart中检查字符串是否为数字 [英] Checking if string is numeric in dart

查看:3171
本文介绍了在dart中检查字符串是否为数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need to find out if a string is numeric in dart. It needs to return true on any valid number type in dart. So far, my solution is

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

是否有一种本地方法?如果没有,还有更好的方法吗?

Is there a native way to do this? If not, is there a better way to do it?

推荐答案

这可以简化一下

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

from double.parse DartDoc

   * Examples of accepted strings:
   *
   *     "3.14"
   *     "  3.14 \xA0"
   *     "0."
   *     ".0"
   *     "-1.e3"
   *     "1234E+7"
   *     "+.12e-9"
   *     "-NaN"

此版本还接受十六进制数字

This version accepts also hexadecimal numbers

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

true

更新

由于现在不推荐使用{onError(String source)},因此您只能使用tryParse:

Since {onError(String source)} is deprecated now you can just use tryParse:

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

这篇关于在dart中检查字符串是否为数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆