Home โบ Java exceptions โบ NumberFormatException
NumberFormatException: causes and fixes
A string could not be parsed as a number, usually by Integer.parseInt or Double.parseDouble.
What it looks like
java.lang.NumberFormatException: For input string: "12a"Extends IllegalArgumentException in java.lang.
What it means
The parse methods of Integer, Long, Double, BigDecimal and friends throw NumberFormatException when the text is not a valid number in the expected format. The message quotes the offending input, which makes empty strings and stray whitespace easy to spot: For input string: "" means the string was empty, and Cannot parse null string means it was null.
Common causes
- Whitespace, a thousands separator or a currency symbol in the text:
" 42","1,000","$5". - An empty or null value from a form field, query parameter or CSV cell.
- A value too large for the type:
Integer.parseInt("3000000000")overflows an int. - A decimal comma in a locale that does not use the dot, or a decimal point passed to
parseInt.
How to fix it
- Trim the input and check for empty before parsing.
- Use
Long.parseLongorBigIntegerwhen values can exceed the int range. - Use
NumberFormat.getInstance(locale)to parse locale-formatted numbers, andBigDecimalfor money. - Catch the exception at the boundary where the text enters the system and turn it into a validation error.
Broken and fixed
int qty = Integer.parseInt(request.getParameter("qty")); // null, "" or " 3" failString raw = request.getParameter("qty");
int qty = (raw == null || raw.isBlank()) ? 1 : Integer.parseInt(raw.trim());๐ Unravel the failing code ๐ Unravel the fix
In Spring and enterprise code
In Spring MVC, a bad number in a @RequestParam int becomes a MethodArgumentTypeMismatchException and a 400 response before your code runs.
Debug it faster
Paste the whole stack trace into the stack trace beautifier to hide framework frames, jump to the root cause and find the first line of your own code. It runs in your browser, so the trace never leaves your machine.
Frequently asked questions
Is NumberFormatException a checked or unchecked exception?
NumberFormatException is an unchecked exception (it extends IllegalArgumentException, which is a RuntimeException), so you are not forced to catch it. Prevent it with validation, or handle it where the input enters the system.
Which package is NumberFormatException in?
It lives in java.lang, so the import is import java.lang.NumberFormatException; (java.lang needs no import).
What is the first thing to check when I see NumberFormatException?
Read the message and the first stack trace line in your own code. The usual causes are: Whitespace, a thousands separator or a currency symbol in the text: " 42", "1,000", "$5"; and An empty or null value from a form field, query parameter or CSV cell.