90

I need to find out if a string is numeric in dart. It needs to return true on any valid number type in dart. So far, my solution is

bool isNumeric(String str) {
  try{
    var value = double.parse(str);
  } on FormatException {
    return false;
  } finally {
    return true;
  }
}

Is there a native way to do this? If not, is there a better way to do it?

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
scrblnrd3
  • 7,228
  • 9
  • 33
  • 64

10 Answers10

124

This can be simpliefied a bit

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

bool isNumeric(String s) {
  if(s == null) {
    return false;
  }
  return double.parse(s, (e) => null) != null;
}
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'

from double.parse DartDoc

   * Examples of accepted strings:
   *
   *     "3.14"
   *     "  3.14 \xA0"
   *     "0."
   *     ".0"
   *     "-1.e3"
   *     "1234E+7"
   *     "+.12e-9"
   *     "-NaN"

This version accepts also hexadecimal numbers

bool isNumeric(String s) {
  if(s == null) {
    return false;
  }

  // TODO according to DartDoc num.parse() includes both (double.parse and int.parse)
  return double.parse(s, (e) => null) != null || 
      int.parse(s, onError: (e) => null) != null;
}

print(int.parse('0xab'));

true

UPDATE

Since {onError(String source)} is deprecated now you can just use tryParse:

bool isNumeric(String s) {
 if (s == null) {
   return false;
 }
 return double.tryParse(s) != null;
}
diegoveloper
  • 93,875
  • 20
  • 236
  • 194
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • 2
    Since the question didn't define what it meant to be numeric, this is definitely a solution, but notice that it will accept `"Infinity"` and `"NaN"` as well. Whether initial '-' should be allowed also depends on the exact definition. If it must also accept `"0x123"`, you can use `num.parse` instead of `double.parse`. – lrn Jun 06 '14 at 16:29
  • Thanks for the hint! I considered asking what should be considered a number. You are right of course. Interesting that `"INFINITY"` is not considered a number but `"NaN"` is. – Günter Zöchbauer Jun 06 '14 at 16:34
  • 1
    It only accepts exactly the output of `double.INFINITY.toString()`, which is "Infinity" (capitalized, but not upper-case). – lrn Jun 06 '14 at 16:38
  • Thanks! This is definitely a better solution than mine. – scrblnrd3 Jun 06 '14 at 18:42
  • 1
    one liner: `bool isNumeric(String s) => s != null && double.tryParse(s) != null;` – Taufik Nur Rahmanda Jan 25 '20 at 11:44
  • 1
    I found the `isNumeric` function so handy that I modified it a bit and put it in a String extension: `bool isDouble() { return double.tryParse(this) != null; }` – Carl Smith May 17 '23 at 19:16
62

In Dart 2 this method is deprecated

int.parse(s, onError: (e) => null)

instead, use

 bool _isNumeric(String str) {
    if(str == null) {
      return false;
    }
    return double.tryParse(str) != null;
  }
Matso Abgaryan
  • 676
  • 5
  • 4
24

Even shorter. Despite the fact it will works with double as well, using num is more accurately.

isNumeric(string) => num.tryParse(string) != null;

num.tryParse inside:

static num tryParse(String input) {
  String source = input.trim();
  return int.tryParse(source) ?? double.tryParse(source);
}
Airon Tark
  • 8,900
  • 4
  • 23
  • 19
22

for anyone wanting a non native way using regex

/// check if the string contains only numbers
 bool isNumeric(String str) {
        RegExp _numeric = RegExp(r'^-?[0-9]+$');
return _numeric.hasMatch(str);
}
Nelson Bwogora
  • 2,225
  • 1
  • 18
  • 21
  • It´s the easiest to apply. I would suggest to put _numeric inside of the functions, because this way it should be plugAndPlay. The result should be: bool isNumeric(String str) { RegExp _numeric = RegExp(r'^-?[0-9]+$'); return _numeric.hasMatch(str); } – Thiago Silva Oct 19 '20 at 14:02
  • Most flexible and universal solution out there ! – Khushal Jun 12 '23 at 07:33
13
if (int.tryParse(value) == null) {
  return 'Only Number are allowed';
}
Ashutosh Pareek
  • 171
  • 1
  • 2
5

Yes, there is a more "sophisticated" way *rsrs*.
extension Numeric on String {
  bool get isNumeric => num.tryParse(this) != null ? true : false;
}

main() {
  print("1".isNumeric); // true
  print("-1".isNumeric); // true
  print("2.5".isNumeric); // true
  print("-2.5".isNumeric); // true
  print("0x14f".isNumeric); // true
  print("2,5".isNumeric); // false
  print("2a".isNumeric); // false
}
3
bool isOnlyNumber(String str) {
  try{
    var value = int.parse(str);
    return true;
  } on FormatException {
    return false;
  } 
}
Anand
  • 4,355
  • 2
  • 35
  • 45
  • 1
    It would be nice to give a brief explanation of how this works / how it solves the problem, and how it's different than existing answers. – starball Dec 24 '22 at 03:21
0
import 'dart:convert';

void main() {
  //------------------------allMatches Example---------------------------------
  print('Example 1');

  //We want to extract ages from the following string:
  String str1 = 'Sara is 26 years old. Maria is 18 while Masood is 8.';

  //Declaring a RegExp object with a pattern that matches sequences of digits
  RegExp reg1 = new RegExp(r'(\d+)');

  //Iterating over the matches returned from allMatches
  Iterable allMatches = reg1.allMatches(str1);
  var matchCount = 0;
  allMatches.forEach((match) {
    matchCount += 1;
    print('Match ${matchCount}: ' + str1.substring(match.start, match.end));
  });

  //------------------------firstMatch Example---------------------------------
  print('\nExample 2');

  //We want to find the first sequence of word characters in the following string:
  //Note: A word character is any single letter, number or underscore
  String str2 = '#%^!_as22 d3*fg%';

  //Declaring a RegExp object with a pattern that matches sequences of word
  //characters
  RegExp reg2 = new RegExp(r'(\w+)');

  //Using the firstMatch function to display the first match found
  Match firstMatch = reg2.firstMatch(str2) as Match;
  print('First match: ${str2.substring(firstMatch.start, firstMatch.end)}');

  //--------------------------hasMatch Example---------------------------------
  print('\nExample 3');

  //We want to check whether a following strings have white space or not
  String str3 = 'Achoo!';
  String str4 = 'Bless you.';

  //Declaring a RegExp object with a pattern that matches whitespaces
  RegExp reg3 = new RegExp(r'(\s)');

  //Using the hasMatch method to check strings for whitespaces
  print(
      'The string "' + str3 + '" contains whitespaces: ${reg3.hasMatch(str3)}');
  print(
      'The string "' + str4 + '" contains whitespaces: ${reg3.hasMatch(str4)}');

  //--------------------------stringMatch Example-------------------------------
  print('\nExample 4');

  //We want to print the first non-digit sequence in the following strings;
  String str5 = '121413dog299toy01food';
  String str6 = '00Tom1231frog';

  //Declaring a RegExp object with a pattern that matches sequence of non-digit
  //characters
  RegExp reg4 = new RegExp(r'(\D+)');

  //Using the stringMatch method to find the first non-digit match:
  String? str5Match = reg4.stringMatch(str5);
  String? str6Match = reg4.stringMatch(str6);
  print('First match for "' + str5 + '": $str5Match');
  print('First match for "' + str6 + '": $str6Match');

  //--------------------------matchAsPrefix Example-----------------------------
  print('\nExample 5');

  //We want to check if the following strings start with the word "Hello" or not:
  String str7 = 'Greetings, fellow human!';
  String str8 = 'Hello! How are you today?';

  //Declaring a RegExp object with a pattern that matches the word "Hello"
  RegExp reg5 = new RegExp(r'Hello');

  //Using the matchAsPrefix method to match "Hello" to the start of the strings
  Match? str7Match = reg5.matchAsPrefix(str7);
  Match? str8Match = reg5.matchAsPrefix(str8);
  print('"' + str7 + '" starts with hello: ${str7Match != null}');
  print('"' + str8 + '" starts with hello: ${str8Match != null}');
}
nivedha
  • 1
  • 1
  • You can Better know about RegExp in this above example and you can find the matches with your strings. – nivedha May 28 '22 at 07:47
0

Building on Matso Abgaryan's answer and Günter Zöchbauer's updated answer,

I can get a ',' (comma) on my numeric soft keyboard while developing mobile apps in flutter, and double.tryParse() can return Nan as well as null - so checking vs null is not enough if a user can enter a comma on a soft numeric keyboard. If a string is empty, using double.tryParse() will produce null - so that edge case will be caught using this function;

bool _isNumeric(String str) {
   if (str == null) {
     return false;
   }
   return double.tryParse(str) is double; 
}

Documentation for tryParse()

tommytucker7182
  • 213
  • 1
  • 5
  • 11
0
bool isNumeric(String s) {
  double? numeric = double.tryParse(s);

  if (numeric == null) {
    return false;
  } else {
    return true;
  }
}
  • 1
    Thank you for your interest in contributing to the Stack Overflow community. This question already has quite a few answers—including one that has been extensively validated by the community. Are you certain your approach hasn’t been given previously? **If so, it would be useful to explain how your approach is different, under what circumstances your approach might be preferred, and/or why you think the previous answers aren’t sufficient.** Can you kindly [edit] your answer to offer an explanation? – Jeremy Caney Aug 14 '23 at 01:01