Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Validating Numeric Strings: Implementing an isNumeric Function

Tech 2

Objective Implement a function to determine if a given string represents a valid numeric value, including integers, decimals, and numbers in scientific notation.

Examples of Valid Inputs "+100", "5e2", "-123", "3.1416", "-1E-16"

Examples of Invalid Inputs "12e", "1a3.14", "1.2.3", "+-5", "12e+5.4"

Specification Analysis A valid numeric string can be decomposed in to distinct components:

  1. An optional sign character (+ or -) at the beginning.
  2. A sequence of digits (0-9) representing the integer part.
  3. An optional decimal point (.) followed by digits for the fractional part.
  4. An optional exponent part introduced by 'e' or 'E', which itself includes an optional sign and must be followed by an integer.

Implementation Strategy The validation logic proceeds by scanning the string sequentially, verifying each component as defined. The approach uses helper methods to parse digit sequences and the exponent section.

Java Implementation

public class NumericStringValidator {

    public static boolean validateNumeric(char[] input) {
        if (input == null || input.length == 0) {
            return false;
        }
        int index = 0;
        // Process optional leading sign
        if (input[0] == '+' || input[0] == '-') {
            index++;
        }
        // Check if string is only a sign
        if (index == input.length) {
            return false;
        }
        // Parse the integer part digits
        index = parseDigits(input, index);

        if (index < input.length) {
            // Check for decimal point or exponent
            if (input[index] == '.') {
                index++;
                index = parseDigits(input, index);
                if (index >= input.length) {
                    return true; // Valid number ending after decimal part
                } else if (index < input.length && (input[index] == 'e' || input[index] == 'E')) {
                    return validateExponent(input, index);
                } else {
                    return false; // Invalid character after decimal part
                }
            } else if (input[index] == 'e' || input[index] == 'E') {
                return validateExponent(input, index);
            } else {
                return false; // Invalid character
            }
        } else {
            // Reached end of string after integer part
            return true;
        }
    }

    private static boolean validateExponent(char[] input, int pos) {
        if (pos >= input.length || (input[pos] != 'e' && input[pos] != 'E')) {
            return false;
        }
        pos++;
        if (pos >= input.length) {
            return false; // Exponent marker at the end
        }
        // Optional sign in exponent
        if (input[pos] == '+' || input[pos] == '-') {
            pos++;
        }
        if (pos >= input.length) {
            return false; // Only sign after exponent marker
        }
        // Must have digits in exponent
        pos = parseDigits(input, pos);
        return pos == input.length; // Valid if exponent ends the string
    }

    private static int parseDigits(char[] input, int startPos) {
        while (startPos < input.length && input[startPos] >= '0' && input[startPos] <= '9') {
            startPos++;
        }
        return startPos;
    }

    public static void main(String[] args) {
        // Test valid cases
        System.out.println(validateNumeric("100".toCharArray()) + " [" + true + "]");
        System.out.println(validateNumeric("123.45e+6".toCharArray()) + " [" + true + "]");
        System.out.println(validateNumeric("+500".toCharArray()) + " [" + true + "]");
        System.out.println(validateNumeric("5e2".toCharArray()) + " [" + true + "]");
        System.out.println(validateNumeric("3.1416".toCharArray()) + " [" + true + "]");
        System.out.println(validateNumeric("600.".toCharArray()) + " [" + true + "]");
        System.out.println(validateNumeric("-.123".toCharArray()) + " [" + true + "]");
        System.out.println(validateNumeric("-1E-16".toCharArray()) + " [" + true + "]");
        System.out.println(validateNumeric("1.79769313486232E+308".toCharArray()) + " [" + true + "]");
        System.out.println();
        // Test invalid cases
        System.out.println(validateNumeric("12e".toCharArray()) + " [" + false + "]");
        System.out.println(validateNumeric("1a3.14".toCharArray()) + " [" + false + "]");
        System.out.println(validateNumeric("1+23".toCharArray()) + " [" + false + "]");
        System.out.println(validateNumeric("1.2.3".toCharArray()) + " [" + false + "]");
        System.out.println(validateNumeric("+-5".toCharArray()) + " [" + false + "]");
        System.out.println(validateNumeric("12e+5.4".toCharArray()) + " [" + false + "]");
    }
}

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.