Fundamentals 16 min read

How to Validate Numeric Strings in Java: Multiple Approaches Explained

This article compares five Java techniques for checking whether a string represents a valid number—including manual character iteration, Integer.parseInt/Double.parseDouble, BigDecimal, regular expressions, and Apache Commons NumberUtils—showing code samples, test cases, and the pros and cons of each method.

FunTester
FunTester
FunTester
How to Validate Numeric Strings in Java: Multiple Approaches Explained

Simple Iteration Method

The isValidNumber method walks through each character of the input string, ensures every character is a digit or a single decimal point, and returns true only when the format is valid. It first rejects null or empty strings, tracks whether a decimal point has already appeared, and fails fast on any non‑digit character.

package practice;

/**
 * Simple utility to verify whether a string is a valid numeric format.
 */
public class Test {
    public static boolean isValidNumber(String str) {
        if (str == null || str.isEmpty()) {
            return false; // empty or null is illegal
        }
        boolean hasDecimalPoint = false;
        for (char ch : str.toCharArray()) {
            if (ch == '.') {
                if (hasDecimalPoint) {
                    return false; // multiple decimal points are illegal
                }
                hasDecimalPoint = true; // first decimal point
            } else if (!Character.isDigit(ch)) {
                return false; // non‑digit character makes it illegal
            }
        }
        return true; // valid numeric format
    }

    public static void main(String[] args) {
        System.out.println("FunTester numeric format check start:");
        System.out.println("Input: 123\tResult: " + isValidNumber("123"));   // true
        System.out.println("Input: 12.3\tResult: " + isValidNumber("12.3")); // true
        System.out.println("Input: 12.3.4\tResult: " + isValidNumber("12.3.4")); // false
        System.out.println("Input: abc\tResult: " + isValidNumber("abc")); // false
    }
}

Running the main method prints:

true
true
false
false

Using Integer.parseInt and Double.parseDouble

Two helper methods demonstrate the standard Java parsing APIs. isValidInteger attempts Integer.parseInt(str) inside a try block and returns true on success, false on NumberFormatException. isValidDouble does the same with Double.parseDouble(str), covering both integers and floating‑point numbers.

package practice;

/**
 * Validate strings as integers or doubles using Java's built‑in parsers.
 */
public class Test {
    public static boolean isValidInteger(String str) {
        try {
            Integer.parseInt(str);
            return true;
        } catch (NumberFormatException e) {
            return false;
        }
    }

    public static boolean isValidDouble(String str) {
        try {
            Double.parseDouble(str);
            return true;
        } catch (NumberFormatException e) {
            return false;
        }
    }

    public static void main(String[] args) {
        System.out.println("FunTester numeric validation:");
        System.out.println("Integer check - Input: 123\tResult: " + isValidInteger("123")); // true
        System.out.println("Integer check - Input: 12.3\tResult: " + isValidInteger("12.3")); // false
        System.out.println("Double check - Input: 12.3\tResult: " + isValidDouble("12.3")); // true
        System.out.println("Double check - Input: abc\tResult: " + isValidDouble("abc")); // false
    }
}

Output:

true
false
true
false

BigDecimal Approach

The isValidBigDecimal method leverages new BigDecimal(str), which can parse integers, decimals, and scientific notation. If construction succeeds, the method returns true; otherwise it catches NumberFormatException and returns false.

package practice;

import java.math.BigDecimal;

/**
 * Validate strings using BigDecimal for high‑precision numeric formats.
 */
public class Test {
    public static boolean isValidBigDecimal(String str) {
        try {
            new BigDecimal(str);
            return true;
        } catch (NumberFormatException e) {
            return false;
        }
    }

    public static void main(String[] args) {
        System.out.println("FunTester high‑precision check:");
        System.out.println("Input: 123.45\tResult: " + isValidBigDecimal("123.45")); // true
        System.out.println("Input: 1e10\tResult: " + isValidBigDecimal("1e10")); // true
        System.out.println("Input: abc\tResult: " + isValidBigDecimal("abc")); // false
    }
}

Output:

true
true
false

Regular Expression Method

The isValidRegex method defines a pattern that accepts an optional sign, optional integer part, optional fractional part, and optional scientific‑notation exponent. It uses Pattern.matches to test the whole string.

package practice;

import java.util.regex.Pattern;

/**
 * Validate numeric strings with a flexible regular expression.
 */
public class Test {
    public static boolean isValidRegex(String str) {
        // ^[+-]?\d*(\.\d+)?([eE][+-]?\d+)?$
        String regex = "^[+-]?\\d*(\\.\\d+)?([eE][+-]?\\d+)?$";
        return Pattern.matches(regex, str);
    }

    public static void main(String[] args) {
        System.out.println("FunTester regex test:");
        System.out.println("Input: 123\tResult: " + isValidRegex("123")); // true
        System.out.println("Input: -12.3\tResult: " + isValidRegex("-12.3")); // true
        System.out.println("Input: 1e10\tResult: " + isValidRegex("1e10")); // true
        System.out.println("Input: abc\tResult: " + isValidRegex("abc")); // false
    }
}

Output:

true
true
true
false

Apache Commons NumberUtils

The isValidNumberWithCommons method delegates to NumberUtils.isCreatable(str), which recognises decimal, hexadecimal, scientific notation, and other numeric formats without custom parsing logic.

import org.apache.commons.lang3.math.NumberUtils;

/**
 * Validate strings using Apache Commons Lang's NumberUtils.
 */
public class Test {
    public static boolean isValidNumberWithCommons(String str) {
        return NumberUtils.isCreatable(str); // supports a wide range of numeric formats
    }

    public static void main(String[] args) {
        System.out.println("FunTester Commons check:");
        System.out.println("Input: 123\tResult: " + isValidNumberWithCommons("123")); // true
        System.out.println("Input: -12.3\tResult: " + isValidNumberWithCommons("-12.3")); // true
        System.out.println("Input: 1e10\tResult: " + isValidNumberWithCommons("1e10")); // true
        System.out.println("Input: abc\tResult: " + isValidNumberWithCommons("abc")); // false
    }
}

Output:

true
true
true
false

Conclusion

All five approaches correctly identify valid numeric strings, but they differ in flexibility and implementation effort. Manual iteration is lightweight and works for simple decimal numbers. The built‑in parseInt / parseDouble methods are concise for standard formats. BigDecimal adds high‑precision support and handles scientific notation. Regular expressions provide the most configurable pattern matching. Apache Commons NumberUtils offers the broadest out‑of‑the‑box coverage with minimal code. Choose the method that best matches the required numeric formats and project dependencies.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaBigDecimalregexString ParsingApache CommonsNumber Validation
FunTester
Written by

FunTester

10k followers, 1k articles | completely useless

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.