Check if a string is numeric in a dart

I need to find out if the string is numeric in the droid. It should return true in any real type of number in the dart. So far my decision has been

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

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

+17
source share
3 answers

It might be a little simplified.

 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' 

from double.parse DartDoc

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

This version also accepts 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

+17
source

In Dart 2, this method is deprecated

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

use instead

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

Even shorter. Although it will work with double , using num more accurate.

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

num.tryParse inside:

 static num tryParse(String input) { String source = input.trim(); return int.tryParse(source) ?? double.tryParse(source); } 
+2
source

Source: https://habr.com/ru/post/970462/


All Articles