Resolve java.lang.NumberFormatException in Java
You resolve java.lang.NumberFormatException: For input string by finding the exact text passed to a numeric parser, deciding what valid input looks like, and rejecting or correcting invalid values before parsing. The exception means Java tried to convert a string to a numeric type, but the string was not in the required format. Start with the stack trace, then handle blank values, whitespace, symbols, decimal points, and out-of-range numbers deliberately.
Use this table to match the exception message to the most likely repair:
| Symptom | Likely Cause | Fix |
|---|---|---|
For input string: "" |
The parser received an empty string. | Check for blank input before parsing and return a required-field error or a chosen default. |
For input string: " 42 " |
The value has leading or trailing whitespace. | Trim it before validating and parsing. |
For input string: "12.5" with Integer.parseInt |
A decimal value is being parsed as an integer. | Use the correct type, such as double or BigDecimal, or require whole numbers. |
For input string: "1,200" or "$20" |
The input contains display formatting or symbols. | Remove only formatting your input contract permits, or parse with a locale-aware formatter. |
| A numeric-looking value still fails | The number exceeds the target type’s range. | Parse into a larger type or validate the allowed range after parsing. |
What NumberFormatException Means
NumberFormatException is a runtime exception thrown when code attempts to convert a string into a numeric type and the string does not have an appropriate numeric format. Oracle’s NumberFormatException API documentation identifies it as a subclass of IllegalArgumentException.
Common parsing methods that can throw it include:
Integer.parseInt(text);
Long.parseLong(text);
Double.parseDouble(text);
new BigDecimal(text);
The exception message usually identifies the bad value:
java.lang.NumberFormatException: For input string: "abc"
That is useful evidence, but do not stop at the message. Find the first line in your own code in the stack trace and inspect the value reaching that parser.
When the message contains "" and the stack trace names Integer.parseInt, the parser received an empty string rather than digits.
An empty string is not zero, and it is not a missing value Java can infer. Your application must decide whether a blank value should produce a validation error, use a documented default, or be treated as an optional field.
How to Fix NumberFormatException Without Hiding Bad Input
Use the following five steps to locate the conversion call, define the field contract, validate numeric grammar, and parse input with the correct Java type.
Step 1: Locate the Exact Conversion Call
Read the stack trace from the top until you reach the first class and line number in your code. That line normally contains a conversion such as:
int quantity = Integer.parseInt(request.getParameter("quantity"));
Do not assume the browser form, file, API payload, or environment variable contains what you expect. Capture the value immediately before parsing during local debugging:
String rawQuantity = request.getParameter("quantity");
System.out.printf(
"quantity raw=[%s], length=%s%n",
rawQuantity,
rawQuantity == null ? "null" : rawQuantity.length()
);
The brackets make whitespace visible, and the length distinguishes "" from " ".
Do not log raw values that may contain passwords, tokens, personal data, or other sensitive information. For production systems, log a field name, length, validation result, and a safely redacted value instead.
I reproduce one malformed value at a time in a clean container or virtual environment because that removes machine-specific noise.
Step 2: Define What the Field Is Allowed to Contain
Before writing a fix, define the field’s contract. For example:
- An order quantity may allow positive whole numbers only.
- A temperature may allow signed decimals.
- A database ID may allow digits only.
- An optional search filter may allow blank input.
- A port number may require a whole number within an application-defined range.
Avoid “fixes” that silently change meaning. Removing every non-digit character from "-12.5" produces "125", which is valid Java syntax but the wrong value.
For a required whole-number field, normalize only harmless whitespace:
String text = rawQuantity == null ? "" : rawQuantity.trim();
Then decide what a blank value means:
if (text.isEmpty()) {
throw new IllegalArgumentException("quantity is required");
}
Trimming is appropriate when surrounding whitespace is not meaningful. It is not a substitute for validation.
Step 3: Validate the Expected Numeric Grammar
Validate based on the type you actually want. If the application accepts ordinary signed base-10 integers, require that pattern explicitly:
if (!text.matches("[+-]?\\d+")) {
throw new IllegalArgumentException(
"quantity must be a whole number, such as 12 or -12"
);
}
This rejects values such as:
12.5
1,200
$12
12 items
It also makes your error message clearer than a raw parser exception.
For a field that must be nonnegative, validation has two parts: first verify the text has integer syntax, then parse it and check the value:
int quantity = Integer.parseInt(text);
if (quantity < 0) {
throw new IllegalArgumentException("quantity cannot be negative");
}
Keep syntax validation and business-rule validation separate. "12.5" is invalid syntax for an integer; "-5" is valid integer syntax but may violate the field’s rule.
Step 4: Parse With the Correct Java Type
Use the parser that matches the input contract.
Integer.parseInt(String) is the standard conversion for a string that should become a Java int:
int count = Integer.parseInt(text);
Use long when the field may exceed the range of int:
long recordId = Long.parseLong(text);
Use BigDecimal for precise decimal values such as money, measurements requiring exact decimal representation, or user-entered rates:
BigDecimal price = new BigDecimal(text);
Avoid double for currency calculations because binary floating-point values cannot represent many decimal fractions exactly.
If you accept decimal floating-point input, check whether special values are appropriate for your application:
double reading = Double.parseDouble(text);
if (!Double.isFinite(reading)) {
throw new IllegalArgumentException("reading must be a finite number");
}
Step 5: Catch the Exception at the Input Boundary
Validate input before parsing when invalid input is expected, such as a web form, command-line argument, CSV file, API request, or configuration variable. Still catch NumberFormatException at the boundary, because numeric range errors can occur even after a syntax check.
This complete helper rejects null, blank, non-integer, and out-of-range input with useful messages:
public static int parseRequiredInt(String raw, String fieldName) {
if (raw == null) {
throw new IllegalArgumentException(fieldName + " is required");
}
String text = raw.trim();
if (text.isEmpty()) {
throw new IllegalArgumentException(fieldName + " is required");
}
if (!text.matches("[+-]?\\d+")) {
throw new IllegalArgumentException(
fieldName + " must be a whole number"
);
}
try {
return Integer.parseInt(text);
} catch (NumberFormatException ex) {
throw new IllegalArgumentException(
fieldName + " is outside the supported integer range",
ex
);
}
}
Use it at the point where external text enters your program:
int quantity = parseRequiredInt(request.getParameter("quantity"), "quantity");
Do not catch the exception and quietly substitute 0 unless zero is explicitly the correct business value. Silent defaults can turn an input error into incorrect data, incorrect pricing, or an unsafe configuration.
Because NumberFormatException extends IllegalArgumentException, an existing catch (IllegalArgumentException ex) block will also catch it. Catch NumberFormatException first when you need a distinct response for bad numeric text:
try {
int value = Integer.parseInt(text);
process(value);
} catch (NumberFormatException ex) {
showValidationError("Enter a whole number.");
} catch (IllegalArgumentException ex) {
showValidationError("The request is invalid.");
}
Common Input Cases That Cause the Exception
Empty values, decimals, display formatting, and numbers outside the target range can all cause NumberFormatException.
Empty and Whitespace-Only Values
Empty or whitespace-only values are common when a form field is optional, a CSV column is missing, an environment variable is unset, or a configuration file contains an empty assignment. String raw = “”; Integer.parseInt(raw); // throws NumberFormatException
String raw = "";
Integer.parseInt(raw); // throws NumberFormatException
Treat null, "", and " " as separate possibilities until you intentionally normalize them:
if (raw == null || raw.trim().isEmpty()) {
// Handle missing input here.
}
Whether the result is an error, a default, or an omitted setting depends on the field’s contract.
Decimal Values Parsed as Integers
Parsing “42.0” with an integer parser fails because integer parsers do not accept a decimal point: Integer.parseInt(“42.0”); // throws NumberFormatException
Integer.parseInt("42.0"); // throws NumberFormatException
If whole numbers are required, reject 42.0 and ask for 42. If fractional values are valid, parse a decimal type instead:
BigDecimal amount = new BigDecimal("42.0");
Do not parse as double and cast to int merely to avoid the exception. That silently truncates values such as "42.9".
Commas, Currency Symbols, and Display Text
A string formatted for people is not automatically valid parser input:
Integer.parseInt("1,200"); // throws NumberFormatException
Integer.parseInt("$1200"); // throws NumberFormatException
For machine-to-machine APIs and configuration files, prefer an unformatted numeric contract such as 1200.
For localized user input, use a locale-aware parser rather than manually stripping punctuation. Manual replacement can produce incorrect results when thousands separators and decimal separators differ by locale.
Numbers Outside the Target Range
A value can contain only digits and still fail:
Integer.parseInt("999999999999"); // throws NumberFormatException
The text is syntactically numeric, but it does not fit in an int. Choose a larger type if the domain permits it:
long value = Long.parseLong("999999999999");
Then validate the application’s business range separately. A long that parses successfully may still be an invalid quantity, ID, or setting for your system.
Handling Input From APIs, Files, and Configuration
The most reliable approach is to parse external input once, near the system boundary, and pass typed values through the rest of the application.
For example, a controller can validate an HTTP parameter before calling service code:
public void createOrder(String rawQuantity) {
int quantity = parseRequiredInt(rawQuantity, "quantity");
if (quantity <= 0) {
throw new IllegalArgumentException("quantity must be greater than zero");
}
orderService.create(quantity);
}
This keeps String handling, whitespace cleanup, numeric syntax checks, range checks, and user-facing error messages in one predictable place.
For CSV and text files, include context in validation errors so you can repair the source data:
public static int parseCsvQuantity(String raw, int lineNumber) {
try {
return parseRequiredInt(raw, "quantity on line " + lineNumber);
} catch (IllegalArgumentException ex) {
throw new IllegalArgumentException(ex.getMessage(), ex);
}
}
For environment variables and configuration, fail at startup with a descriptive error instead of allowing a later failure deep in application code. A configuration error should identify the setting name, not just report that parsing failed.
Resolving the Provisioning Server Installer Case
A NumberFormatException can also appear in third-party Java installers, where application startup scripts or environment output interfere with installer input.
For Broadcom Provisioning Server 14.5 on Linux, the documented console invocation from the product’s Linux installation directory is:
./setuplinux.bin -console
If the installation reports an error, inspect the installer log at:
/tmp/imps_server_install.log
When that log contains NumberFormatException: For input string: "" at Integer.parseInt, check /etc/profile for commands that print blank lines or system-release text during shell startup. The documented remedy for this specific installer is to remove or comment out these lines and other occurrences of echo "":
# echo ""
# cat /etc/system-release
# echo ""
Open a new shell after changing the profile, rerun the installer, and confirm that the installer no longer writes the parsing exception to its log. Do not apply this profile change as a general Java fix; it addresses this installer environment behavior.
How to Confirm the Fix and Prevent Recurrence
After changing the code, test both valid and invalid input intentionally.
- Test an ordinary valid value such as
"42". - Test leading and trailing whitespace such as
" 42 ". - Test an empty string and whitespace-only input.
- Test letters, symbols, commas, and decimal values.
- Test a value beyond the target numeric type’s range.
- Confirm the application returns a useful validation message rather than a stack trace or an unintended default.
A compact JUnit test suite for the helper might look like this:
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import org.junit.jupiter.api.Test;
class NumberParserTest {
@Test
void parsesTrimmedInteger() {
assertEquals(42, parseRequiredInt(" 42 ", "quantity"));
}
@Test
void rejectsBlankValue() {
assertThrows(
IllegalArgumentException.class,
() -> parseRequiredInt(" ", "quantity")
);
}
@Test
void rejectsDecimalForIntegerField() {
assertThrows(
IllegalArgumentException.class,
() -> parseRequiredInt("12.5", "quantity")
);
}
@Test
void rejectsOutOfRangeInteger() {
assertThrows(
IllegalArgumentException.class,
() -> parseRequiredInt("999999999999", "quantity")
);
}
}
Keep numeric parsing close to the input boundary, make each field’s accepted format explicit, and test malformed values whenever you add a new input source.
Keep the formatted result for display rather than sending it to Integer.parseInt, because output such as "1,200" is not plain integer input. Next, add tests for the malformed values your users, files, or integrations can actually send.
Frequently Asked Questions
How can I effectively handle NumberFormatException in Java?
Handle it by validating external text before parsing, using the correct numeric type, and catching NumberFormatException at the input boundary for values that still cannot be parsed. Return a field-specific message such as “quantity must be a whole number” rather than exposing a stack trace. Since NumberFormatException extends IllegalArgumentException, a broad IllegalArgumentException handler catches it too, but a dedicated catch can provide a better numeric-input response.
How do I fix “input string was not in a correct format”?
Find the parser call in the stack trace and inspect the exact raw value passed to it. Check first for blank text, whitespace, commas, decimal points, currency symbols, and values too large for the destination type. Then either normalize input that your contract permits, such as surrounding whitespace, or reject the value with a clear validation error.
How do I convert a numeric value to a string in Java?
Use String.valueOf(value) for most numeric values:
String text = String.valueOf(42);
For an int, Integer.toString(value) is also appropriate. Converting a numeric primitive to a string is the reverse of parsing and does not cause NumberFormatException.
How do I format numbers in Java?
Use NumberFormat when producing numbers for display, especially when grouping separators, currency symbols, or locale rules matter. The formatted result is for display rather than plain numeric parser input: NumberFormat formatter = NumberFormat.getNumberInstance(Locale.US); String displayValue = formatter.format(1200);
NumberFormat formatter = NumberFormat.getNumberInstance(Locale.US);
String displayValue = formatter.format(1200);
