A numeric string is a string that represents a number. Numeric strings can contain digits (0-9) and may also include a decimal point, a minus sign (for negative numbers), and an optional exponential notation (for very large or small numbers).
In simple words, a numeric string is just a number in string format.
Examples of valid numeric strings:
'123',
'0.123',
'4.234,345',
'-33.33',
'+44.44'
To check whether a string is a numeric string, you can use the double.tryParse() method. If the return equals null, then the input is not a numeric string; otherwise, it is.
if(double.tryParse(String input) == null){
print('The input is not a numeric string');
} else {
print('Yes, it is a numeric string');
}
Example
The code:
void main() {
var a = '-33.230393399';
var b = 'ABC123';
if (double.tryParse(a) != null) {
print('a is a numeric string');
} else {
print('a is NOT a numeric string');
}
if (double.tryParse(b) != null) {
print('b is a numeric string');
} else {
print('b is NOT a numeric string');
}
}
Output:
a is a numeric string
b is NOT a numeric string
Hope this helps. Further reading:
- Dart: Convert Class Instances (Objects) to Maps and Vice Versa
- Flutter & Dart: Regular Expression Examples
- Create a Custom NumPad (Number Keyboard) in Flutter
- Flutter: Creating OTP/PIN Input Fields (2 approaches)
- Flutter: Making Beautiful Chat Bubbles (2 Approaches)
You can also take a tour around our Flutter topic page and Dart topic page to see the latest tutorials and examples.