Validate Numeric number in Java

There are many situation where we require to validate numeric number while doing development. You can achieve it by writing regular expression and in corporate it into your code.

Following example shows you, how to validate numeric number using java. A numeric number can start with + or - having digits at starting and there can be . in betwwen and ends with numeric digits.

We have used regular expression as - ^[-+]?[0-9]*\\.?[0-9]+$ , where
^[-+]?: Starts with an optional "+" or "-" sign.
[0-9]*: May have one or more digits.
 \\.? : May contain an optional "." (decimal point) character.
[0-9]+$ : ends with numeric digit.

Java Program to validate Numeric number : 
package com.anuj.utils;

import java.util.regex.Pattern;
import java.util.regex.Matcher;

public class NumericValidator {
    static Pattern p;
    static Matcher m;

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub

        String number = "12345678";
        // String number = "a12345678";
        boolean validNumber = isNumeric(number);

        if (validNumber) {
            System.out.println("String is numeric");
        } else {
            System.out.println("String is not numeric");
        }
    }

    public static boolean isNumeric(String number) {
        boolean isValid = false;
        /*
         * Number: A numeric value will have following format: ^[-+]?: Starts
         * with an optional "+" or "-" sign. [0-9]*: May have one or more
         * digits. \\.? : May contain an optional "." (decimal point) character.
         * [0-9]+$ : ends with numeric digit.
         */

        String exp = "^[-+]?[0-9]*\\.?[0-9]+$";
        CharSequence str = number;
        p = Pattern.compile(exp);
        m = p.matcher(str);
        if (m.matches()) {
            isValid = true;
        }
        return isValid;
    }
}

No comments:

Post a Comment