Check if a given string is a valid number (Integer or Floating Point) | SET 1(Basic approach)

10 Oct, 2019
Validate if a given string is numeric.
Examples:
Input : str = "11.5"
Output : true

Input : str = "abc"
Output : false

Input : str = "2e10"
Output : true

Input : 10e5.4
Output : false

The following cases need to be handled in the code.
Ignore the leading and trailing white spaces.Ignore the ‘+’, ‘-‘ and’.’ at the start.Ensure that the characters in the string belong to {+, -, ., e, [0-9]}Ensure that no ‘.’ comes after ‘e’.A dot character ‘.’ should be followed by a digit.The character ‘e’ should be followed either by ‘+’, ‘-‘, or a digit.
Ignore the leading and trailing white spaces.
Ignore the ‘+’, ‘-‘ and’.’ at the start.
Ensure that the characters in the string belong to {+, -, ., e, [0-9]}
Ensure that no ‘.’ comes after ‘e’.
A dot character ‘.’ should be followed by a digit.
The character ‘e’ should be followed either by ‘+’, ‘-‘, or a digit.
Below is implementation of above steps.
C++
Java
Python3
C#
// C++ program to check if input number// is a valid number#include <bits/stdc++.h>#include <iostream>using namespace std;  int valid_number(string str){    int i = 0, j = str.length() - 1;      // Handling whitespaces    while (i < str.length() && str[i] == ' ')        i++;    while (j >= 0 && str[j] == ' ')        j--;      if (i > j)        return 0;      // if string is of length 1 and the only    // character is not a digit    if (i == j && !(str[i] >= '0' && str[i] <= '9'))        return 0;      // If the 1st char is not '+', '-', '.' or digit    if (str[i] != '.' && str[i] != '+'        && str[i] != '-' && !(str[i] >= '0' && str[i] <= '9'))        return 0;      // To check if a '.' or 'e' is found in given    // string. We use this flag to make sure that    // either of them appear only once.    bool flagDotOrE = false;      for (i; i <= j; i++) {        // If any of the char does not belong to        // {digit, +, -, ., e}        if (str[i] != 'e' && str[i] != '.'            && str[i] != '+' && str[i] != '-'            && !(str[i] >= '0' && str[i] <= '9'))            return 0;          if (str[i] == '.') {            // checks if the char 'e' has already            // occurred before '.' If yes, return 0.            if (flagDotOrE == true)                return 0;              // If '.' is the last character.            if (i + 1 > str.length())                return 0;              // if '.' is not followed by a digit.            if (!(str[i + 1] >= '0' && str[i + 1] <= '9'))                return 0;        }          else if (str[i] == 'e') {            // set flagDotOrE = 1 when e is encountered.            flagDotOrE = true;              // if there is no digit before 'e'.            if (!(str[i - 1] >= '0' && str[i - 1] <= '9'))                return 0;              // If 'e' is the last Character            if (i + 1 > str.length())                return 0;              // if e is not followed either by            // '+', '-' or a digit            if (str[i + 1] != '+' && str[i + 1] != '-'                && (str[i + 1] >= '0' && str[i] <= '9'))                return 0;        }    }      /* If the string skips all above cases, then     it is numeric*/    return 1;}  // Driver codeint main(){    char str[] = "0.1e10";    if (valid_number(str))        cout << "true";    else        cout << "false";    return 0;}  // This code is contributed by rahulkumawat2107
// Java program to check if input number// is a valid numberimport java.io.*;import java.util.*;  class GFG {    public boolean isValidNumeric(String str)    {        str = str.trim(); // trims the white spaces.          if (str.length() == 0)            return false;          // if string is of length 1 and the only        // character is not a digit        if (str.length() == 1 && !Character.isDigit(str.charAt(0)))            return false;          // If the 1st char is not '+', '-', '.' or digit        if (str.charAt(0) != '+' && str.charAt(0) != '-'            && !Character.isDigit(str.charAt(0))            && str.charAt(0) != '.')            return false;          // To check if a '.' or 'e' is found in given        // string. We use this flag to make sure that        // either of them appear only once.        boolean flagDotOrE = false;          for (int i = 1; i < str.length(); i++) {            // If any of the char does not belong to            // {digit, +, -, ., e}            if (!Character.isDigit(str.charAt(i))                && str.charAt(i) != 'e' && str.charAt(i) != '.'                && str.charAt(i) != '+' && str.charAt(i) != '-')                return false;              if (str.charAt(i) == '.') {                // checks if the char 'e' has already                // occurred before '.' If yes, return 0.                if (flagDotOrE == true)                    return false;                  // If '.' is the last character.                if (i + 1 >= str.length())                    return false;                  // if '.' is not followed by a digit.                if (!Character.isDigit(str.charAt(i + 1)))                    return false;            }              else if (str.charAt(i) == 'e') {                // set flagDotOrE = 1 when e is encountered.                flagDotOrE = true;                  // if there is no digit before 'e'.                if (!Character.isDigit(str.charAt(i - 1)))                    return false;                  // If 'e' is the last Character                if (i + 1 >= str.length())                    return false;                  // if e is not followed either by                // '+', '-' or a digit                if (!Character.isDigit(str.charAt(i + 1))                    && str.charAt(i + 1) != '+'                    && str.charAt(i + 1) != '-')                    return false;            }        }          /* If the string skips all above cases, then           it is numeric*/        return true;    }      /* Driver Function to test isValidNumeric function */    public static void main(String[] args)    {        String input = "0.1e10";        GFG gfg = new GFG();        System.out.println(gfg.isValidNumeric(input));    }}
[/sourcecode]
# Python3 program to check if input number# is a valid numberdef valid_number(str):    i = 0    j = len(str) - 1      # Handling whitespaces    while i<len(str) and str[i] == ' ':        i += 1    while j >= 0 and str[j] == ' ':        j -= 1      if i > j:        return False      # if string is of length 1 and the only    # character is not a digit    if (i == j and not(str[i] >= '0' and                        str[i] <= '9')):        return False      # If the 1st char is not '+', '-', '.' or digit    if (str[i] != '.' and str[i] != '+' and         str[i] != '-' and not(str[i] >= '0' and         str[i] <= '9')):        return False      # To check if a '.' or 'e' is found in given    # string.We use this flag to make sure that    # either of them appear only once.    flagDotOrE = False      for i in range(j + 1):                  # If any of the char does not belong to        # {digit, +, -,., e}        if (str[i] != 'e' and str[i] != '.' and             str[i] != '+' and str[i] != '-' and not           (str[i] >= '0' and str[i] <= '9')):            return False          if str[i] == '.':                          # check if the char e has already            # occured before '.' If yes, return 0            if flagDotOrE:                return False            if i + 1 > len(str):                return False            if (not(str[i + 1] >= '0' and                     str[i + 1] <= '9')):                return False        elif str[i] == 'e':                          # set flagDotOrE = 1 when e is encountered.            flagDotOrE = True              # if there is no digit before e            if (not(str[i - 1] >= '0' and                     str[i - 1] <= '9')):                return False                              # if e is the last character            if i + 1 > len(str):                return False                              # if e is not followed by            # '+', '-' or a digit            if (str[i + 1] != '+' and str[i + 1] != '-' and                (str[i + 1] >= '0' and str[i] <= '9')):                return False                      # If the string skips all the    # above cases, it must be a numeric string    return True  # Driver Codeif __name__ == '__main__':    str = "0.1e10"    if valid_number(str):        print('true')    else:        print('false')  # This code is contributed by# chaudhary_19 (Mayank Chaudhary)
// C# program to check if input number// is a valid numberusing System;
class GFG {public Boolean isValidNumeric(String str){str = str.Trim(); // trims the white spaces.
if (str.Length == 0)return false;
// if string is of length 1 and the only// character is not a digitif (str.Length == 1 && !char.IsDigit(str[0]))return false;
// If the 1st char is not ‘+’, ‘-‘, ‘.’ or digitif (str[0] != ‘+’ && str[0] != ‘-‘&& !char.IsDigit(str[0]) && str[0] != ‘.’)return false;
// To check if a ‘.’ or ‘e’ is found in given// string. We use this flag to make sure that// either of them appear only once.Boolean flagDotOrE = false;
for (int i = 1; i < str.Length; i++) {
// If any of the char does not belong to
// {digit, +, -, ., e}
if (!char.IsDigit(str[i]) && str[i] != 'e'
&& str[i] != '.' && str[i] != '+'
&& str[i] != '-')
return false;
if (str[i] == '.') {
// checks if the char 'e' has already
// occurred before '.' If yes, return 0.
if (flagDotOrE == true)
return false;
// If '.' is the last character.
if (i + 1 >= str.Length)return false;
// if ‘.’ is not followed by a digit.if (!char.IsDigit(str[i + 1]))return false;}
else if (str[i] == ‘e’) {// set flagDotOrE = 1 when e is encountered.flagDotOrE = true;
// if there is no digit before ‘e’.if (!char.IsDigit(str[i – 1]))return false;
// If ‘e’ is the last Characterif (i + 1 >= str.Length)return false;
// if e is not followed either by// ‘+’, ‘-‘ or a digitif (!char.IsDigit(str[i + 1]) && str[i + 1] != ‘+’&& str[i + 1] != ‘-‘)return false;}}
/* If the string skips all above cases,then it is numeric*/return true;}
// Driver Codepublic static void Main(String[] args){String input = “0.1e10”;GFG gfg = new GFG();Console.WriteLine(gfg.isValidNumeric(input));}}
// This code is contributed by Rajput-Ji
true

Time Complexity: O(n)
This article is contributed by Saloni Baweja. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
memcpycommand
rahulkumawat2107
AdityaKakoti
gp6
Rajput-Ji
chaudhary_19
Strings
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Top 50 String Coding Problems for Interviews
What is Data Structure: Types, Classifications and Applications
Print all the duplicates in the input string
Print all subsequences of a string
A Program to check if strings are rotations of each other or not
String class in Java | Set 1
Find if a string is interleaved of two other strings | DP-33
Find the smallest window in a string containing all characters of another string
Remove first and last character of a string in Java
Convert character array to string in C++