Algorithm


  1. Input: Accept a string as input.

  2. Initialize Variables:

    • Initialize a boolean variable, let's call it isNumeric, to true.
  3. Iterate Through Characters:

    • Use a loop to iterate through each character in the input string.
  4. Check Each Character:

    • For each character, check if it is a numeric digit.
      • You can use the Character.isDigit(char) method to check if a character is a digit.
      • If a character is not a digit, set isNumeric to false and break out of the loop.
  5. Output:

    • After the loop, if isNumeric is still true, then the entire string is numeric.
  6. Print/Return Result:

    • Print or return the result based on the value of isNumeric.

 

Code Examples

#1 Code Example- Java Programing Check if a string is numeric

Code - Java Programming

public class Numeric {

    public static void main(String[] args) {

        String string = "12345.15";
        boolean numeric = true;

        try {
            Double num = Double.parseDouble(string);
        } catch (NumberFormatException e) {
            numeric = false;
        }

        if(numeric)
            System.out.println(string + " is a number");
        else
            System.out.println(string + " is not a number");
    }
}
Copy The Code & Try With Live Editor

Output

x
+
cmd
12345.15 is a number

#2 Code Example- Check if a string is numeric or not using regular expressions (regex)

Code - Java Programming

public class Numeric {

    public static void main(String[] args) {

        String string = "-1234.15";
        boolean numeric = true;

        numeric = string.matches("-?\\d+(\\.\\d+)?");

        if(numeric)
            System.out.println(string + " is a number");
        else
            System.out.println(string + " is not a number");
    }
}
Copy The Code & Try With Live Editor

Output

x
+
cmd
-1234.15 is a number
Advertisements

Demonstration


Java Programing Example to Check if a String is Numeric-DevsEnv