OneBite.Dev - Coding blog in a bite size

Check If A String Contains Only Numbers In Dart

Code snippet for how to Check If A String Contains Only Numbers In Dart with sample and detail explanation

In the Dart programming language, you may find yourself in a situation where you need to check if a string contains only numbers. This is a common problem in coding that is relevant in various scenarios, such as data validation or user input verification.

Code snippet: Checking if a String Contains Only Numbers in Dart

Here is a simple Dart code snippet that checks whether a string contains only numbers:

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

You can use this function to check if a string contains only numbers. For instance: print(isNumeric("12345")); will return True while print(isNumeric("123abc45")); will return False.

Code Explanation: Checking if a String Contains Only Numbers in Dart

This simple function named isNumeric takes a string s as a parameter.

The first thing the function does is check if the string is null. If the string is null, the function returns false. This is because a null string does not contain any numbers.

Next, double.tryParse(s) attempts to parse the string to a double. If the string can be parsed to a number (integer or decimal), then double.tryParse(s) will return the number else it will return null.

If double.tryParse(s) returns a number, it means that the string contains only numbers, so the function will return true. Otherwise, the function returns false, implying that the string does not contain only numbers.

When applied, this function can help sort or validate numerical data from a batch of strings in your Dart application. Remember, effective data validation is a critical aspect of ensuring your application’s reliability and robustness.

dart