{

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


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

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 a String is Numeric or not

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

The tryParse method converts the string literal into a number. You can also use the parse method. tryParse returns null if the string is 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 character
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 the 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.





Related posts

How to convert Double to Integer or Integer to double in Dart| Flutter By Example

Perl How to: Find a Given Variable String is numeric or not

Dart/Flutter: Check if String is Empty, Null, or Blank example

How to generate Unique Id UUID in Dart or Flutter Programming| Dart or Flutterby Example

How to Sort List of numbers or String in ascending and descending in Dart or Flutter example

Dart Enum comparison operator| Enum compareByIndex example| Flutter By Example

Dart Example - Program to check Leap year or not