Skip to content
Related Articles
Get the best out of our app
GeeksforGeeks App
Open App
geeksforgeeks
Browser
Continue

Related Articles

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

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

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.

  1. Ignore the leading and trailing white spaces.
  2. Ignore the ‘+’, ‘-‘ and’.’ at the start.
  3. Ensure that the characters in the string belong to {+, -, ., e, [0-9]}
  4. Ensure that no ‘.’ comes after ‘e’.
  5. A dot character ‘.’ should be followed by a digit.
  6. The character ‘e’ should be followed either by ‘+’, ‘-‘, or a digit.

Below is implementation of above steps. 

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 code
int main()
{
    char str[] = "0.1e10";
    if (valid_number(str))
        cout << "true";
    else
        cout << "false";
    return 0;
}
 
// This code is contributed by rahulkumawat2107

Java




// Java program to check if input number
// is a valid number
import 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));
    }
}

Python3




# Python3 program to check if input number
# is a valid number
def 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
            # occurred 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 Code
if __name__ == '__main__':
    str = "0.1e10"
    if valid_number(str):
        print('true')
    else:
        print('false')
 
# This code is contributed by
# chaudhary_19 (Mayank Chaudhary)

C#




// C# program to check if input number
// is a valid number
using 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 digit
        if (str.Length == 1 && !char.IsDigit(str[0]))
            return false;
 
        // If the 1st char is not '+', '-', '.' or digit
        if (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 Character
                if (i + 1 >= str.Length)
                    return false;
 
                // if e is not followed either by
                // '+', '-' or a digit
                if (!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 Code
    public 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

Javascript




// Javascript code for the above approach
 
function valid_number(str) {
  let i = 0;
  let j = str.length - 1;
 
  // Handling whitespaces
  while (i < str.length && str[i] == ' ') {
    i++;
  }
  while (j >= 0 && str[j] == ' ') {
    j--;
  }
 
  if (i > j) {
    return false;
  }
 
  // if string is of length 1 and the only character is not a digit
  if (i == j && !(str[i] >= '0' && str[i] <= '9')) {
    return false;
  }
 
  // If the 1st char is not '+', '-', '.' or digit
  if (
    str[i] != '.' &&
    str[i] != '+' &&
    str[i] != '-' &&
    !(str[i] >= '0' && 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.
  let flagDotOrE = false;
 
  for (let k = 0; k <= j; k++) {
    // If any of the char does not belong to {digit, +, -,., e}
    if (
      str[k] != 'e' &&
      str[k] != '.' &&
      str[k] != '+' &&
      str[k] != '-' &&
      !(str[k] >= '0' && str[k] <= '9')
    ) {
      return false;
    }
 
    if (str[k] == '.') {
      // check if the char e has already occurred before '.'
      // If yes, return false
      if (flagDotOrE) {
        return false;
      }
      if (k + 1 > str.length) {
        return false;
      }
      if (!(str[k + 1] >= '0' && str[k + 1] <= '9')) {
        return false;
      }
    } else if (str[k] == 'e') {
      // set flagDotOrE = true when 'e' is encountered.
      flagDotOrE = true;
 
      // if there is no digit before 'e'
      if (!(str[k - 1] >= '0' && str[k - 1] <= '9')) {
        return false;
      }
 
      // if 'e' is the last character
      if (k + 1 > str.length) {
        return false;
      }
 
      // if 'e' is not followed by '+', '-' or a digit
      if (
        str[k + 1] != '+' &&
        str[k + 1] != '-' &&
        !(str[k + 1] >= '0' && str[k + 1] <= '9')
      ) {
        return false;
      }
    }
  }
 
  // If the string skips all the above cases, it must be a numeric string
  return true;
}
 
// Driver Code
let str = "0.1e10";
if (valid_number(str)) {
  console.log("true");
} else {
  console.log("false");
}
 
// This code is contributed by adityashatmfh

Output:

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 write.geeksforgeeks.org or mail your article to review-team@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.


My Personal Notes arrow_drop_up
Last Updated : 09 Mar, 2023
Like Article
Save Article
Similar Reads
Related Tutorials