Dart Check String isNumeric



When value from object must being valid for each data type, sometimes we need function to check the value was the same with data type needed or not. For example, we will check value isNumeric or not.


Function

bool isNumeric(String s) {
  if(s == null) {
    return false;
  }
  return double.parse(s, (e) => null) != null;
}


Run

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

 

Result

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' 


Source :

https://stackoverflow.com/questions/24085385/checking-if-string-is-numeric-in-dart

Comments