{

Dart| Flutter How to: Find a Given String is numeric or not


This tutorial explains How to check given string is a number or not.

You can check my previous post, on How to Convert String to Number in dart.

Dart How to check whether String is Numeric or not

This approach uses the parse method of double for floating and number for without decimals

The tryParse method converts string literal into a number. You can also use the parse method. tryParse returns null if the string not able to convert into a number. parse throws Exception if the string is not parsable.

Here is an example isNumeric Extension method on the String class

extension NumericString on String {
  bool get isNumeric => str.tryParse(this) != null ? true : false;
}

void main() {
  print(("abc").isNumeric); // false
  print(("123").isNumeric); // true
  print(("a123").isNumeric); // false
}

Check String is Number using RegExp

Regular Expression in Dart provides given input against the matching pattern. hasMatch method test pattern and return a boolean result

Here, the Regular express used for Checking a given string is a number or not used below

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

r followed by an enclosed regular expression pattern.

  • r represents a regular expression
  • ^: Begin of string or line
  • $: End of string or line
  • [0-9]: Allowed numbers from 0 to 9 only
      • : one more characters
RegExp _numeric = RegExp(r'^-?[0-9]+$');

bool isNumeric(String str) {
  return _numeric.hasMatch(str);
}

void main() {
  print(isNumeric("abc")); // false
  print(isNumeric("123")); // true
  print(isNumeric("a123")); // false
}

Conclusion

Learned how to check given string is numeric or not.

  • using tryParse or parse method
  • use Regular Expressions in dart
THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.