Tutorials Logic, IN info@tutorialslogic.com

NumberFormatException in Java: Causes and Safe Parsing Fixes

What is This Error?

NumberFormatException occurs when Java numeric parsing receives text that does not match the requested number type or falls outside that type range.

Inspect the exact input, including whitespace and hidden characters. Then choose the parser that matches the data: parseInt for whole numbers, parseDouble for approximate decimals, and BigDecimal for money.

User input and external data should be treated as untrusted. Normalize it, reject blank values, catch NumberFormatException at the input boundary, and return a clear validation message.

The NumberFormatException is thrown when you try to convert a String to a numeric type (int, long, double, etc.) but the string doesn't contain a valid number. It's a subclass of IllegalArgumentException.

Common Causes

  • String contains letters or special characters
  • Parsing a decimal string as integer (e.g., "12.5" with parseInt)
  • String has leading/trailing whitespace
  • Empty string or null passed to parse method
  • Number exceeds the type's range (overflow)

Quick Fix (TL;DR)

Immediate Fix: NumberFormatException

Immediate Fix: NumberFormatException
// Wrong Problem
int num = Integer.parseInt("abc"); // NumberFormatException!

// Correct Solution 1: try-catch
try {
    int num = Integer.parseInt(input.trim());
} catch (NumberFormatException e) {
    System.out.println("Invalid number: " + input);
}

// Correct Solution 2: Validate first
if (input.matches("-?\\d+")) {
    int num = Integer.parseInt(input);
}

Common Scenarios & Solutions

Failure: Crashes if user types twenty

Failure: Crashes if user types twenty
Scanner scanner = new Scanner(System.in);
System.out.print("Enter age: ");
String input = scanner.nextLine();
int age = Integer.parseInt(input); // Crashes if user types "twenty"!

Number Format Exception Correction 1

Number Format Exception Correction 1
Scanner scanner = new Scanner(System.in);
int age = -1;

while (age < 0) {
    System.out.print("Enter age: ");
    String input = scanner.nextLine().trim();
    try {
        age = Integer.parseInt(input);
        if (age < 0 || age > 150) {
            System.out.println("Please enter a valid age (0-150)");
            age = -1;
        }
    } catch (NumberFormatException e) {
        System.out.println("Invalid input. Please enter a number.");
    }
}
System.out.println("Age: " + age);

Failure: NumberFormatException! 19.99 is not an int

Failure: NumberFormatException! 19.99 is not an int
String price = "19.99";
int p = Integer.parseInt(price); // NumberFormatException! "19.99" is not an int

Correction: Parse as double

Correction: Parse as double
String price = "19.99";

// Correct Parse as double
double p = Double.parseDouble(price); // 19.99

// Correct Or parse as int after truncating
int pInt = (int) Double.parseDouble(price); // 19

// Correct Use BigDecimal for money
BigDecimal bd = new BigDecimal(price); // Exact representation

Failure: Has spaces

Failure: Has spaces
String input = " 42 "; // Has spaces!
int num = Integer.parseInt(input); // NumberFormatException!

Correction: Always trim first

Correction: Always trim first
String input = " 42 ";
int num = Integer.parseInt(input.trim()); // Correct Always trim first!

Correction: Reusable safe parse method

Correction: Reusable safe parse method
// Correct Reusable safe parse method
public static Optional<Integer> safeParseInt(String s) {
    if (s == null || s.trim().isEmpty()) return Optional.empty();
    try {
        return Optional.of(Integer.parseInt(s.trim()));
    } catch (NumberFormatException e) {
        return Optional.empty();
    }
}

// Usage
safeParseInt("42").ifPresent(n -> System.out.println("Parsed: " + n));
safeParseInt("abc").ifPresentOrElse(
    n -> System.out.println(n),
    () -> System.out.println("Invalid number")
);

Best Practices to Avoid This Error

  • Always trim() before parsing - Remove leading/trailing whitespace
  • Validate with regex before parsing - Use matches("-?\d+") for integers
  • Use try-catch for user input - Users can type anything
  • Use the right parse method - parseInt for int, parseDouble for decimals
  • Create safe parse helper methods - Reusable validation logic
  • Use BigDecimal for money - Avoids floating-point precision issues
  • Check for null/empty before parsing - Prevent NullPointerException too

Reusable Safe Integer Parser

Reusable Safe Integer Parser
import java.util.OptionalInt;

class SafeIntegerParser {
    static OptionalInt parseInteger(String raw) {
        if (raw == null || raw.isBlank()) {
            return OptionalInt.empty();
        }

        try {
            return OptionalInt.of(Integer.parseInt(raw.trim()));
        } catch (NumberFormatException exception) {
            return OptionalInt.empty();
        }
    }

    public static void main(String[] args) {
        parseInteger(" 42 ").ifPresentOrElse(
            value -> System.out.println("Parsed: " + value),
            () -> System.out.println("Enter a whole number")
        );
    }
}
  • The parser handles null, blank, whitespace, invalid text, and overflow.
  • Keep the validation message at the UI or API boundary.

Use the Correct Numeric Type

Use the Correct Numeric Type
import java.math.BigDecimal;

class PriceParser {
    public static void main(String[] args) {
        String quantityText = "12";
        String priceText = "19.99";

        int quantity = Integer.parseInt(quantityText);
        BigDecimal price = new BigDecimal(priceText);

        System.out.println(quantity);
        System.out.println(price);
    }
}
  • Integer.parseInt("19.99") fails because a decimal is not an integer.
  • BigDecimal is appropriate when decimal precision matters.
Before you move on

NumberFormatException in Java: Causes and Safe Parsing Fixes Mastery Check

5 checks
  • Print or inspect the exact raw string.
  • Reject null and blank input before parsing.
  • Trim surrounding whitespace when it is not meaningful.
  • Choose a parser matching integer, decimal, or monetary data.
  • Handle overflow as well as nonnumeric characters.

Try this next

Core Java Number Format Exception Repair Drills

0 of 2 completed

  1. Process " 42 ", "19.99", an empty string, and an integer beyond the int range. Report integer, decimal, missing, or out-of-range without an uncaught exception. Normalize whitespace first, then choose a parser that matches the accepted grammar and range.
  2. Write a parseInt method that returns OptionalInt for valid input and an empty result for rejected input, then test signs, whitespace, letters, and overflow. Catch NumberFormatException at the input boundary rather than around unrelated business logic.

Core Java Questions Learners Ask

It's thrown when Integer.parseInt(), Double.parseDouble(), or similar methods receive a string that doesn't represent a valid number "" like "abc", "12.5" (for parseInt), or strings with spaces.

First parse as double, then cast: (int) Double.parseDouble("12.5") gives 12. Or use Math.round() to round: (int) Math.round(Double.parseDouble("12.5")) gives 13.

Use regex: input.matches("-?\d+") for integers, input.matches("-?\d+(\.\d+)?") for decimals. Or use try-catch which is simpler for most cases.

Browse Free Tutorials

Explore 500+ free tutorials across 20+ languages and frameworks.