Keywords: Java | Numerical Parsing | Type Conversion | NumberFormatException | Floating-Point
Abstract: This article provides an in-depth analysis of why Integer.parseInt() throws NumberFormatException when parsing decimal numbers in Java, and presents correct solutions using Double.parseDouble() and Float.parseFloat(). Through code examples and technical explanations, it explores the fundamental differences between integer and floating-point data representations, as well as truncation behavior during type conversion. The paper also compares performance characteristics of different parsing approaches and their appropriate use cases.
Problem Analysis
In Java programming, when attempting to parse a string containing decimal points using Integer.parseInt("0.01"), a NumberFormatException is thrown. This occurs because the Integer.parseInt() method is designed specifically for parsing integer strings, while 0.01 represents a decimal number that falls outside the integer domain.
Root Cause
Integer data types (such as int) in Java are used to represent numbers without fractional components. When a string contains a decimal point, it represents a rational number (fraction), which integer types cannot store. The Integer.parseInt() method performs strict format validation during parsing and immediately throws an exception upon encountering non-numeric characters like decimal points.
Correct Solution
For numeric strings containing decimal points, developers should use Double.parseDouble() or Float.parseFloat() methods:
String s = "0.01";
double d = Double.parseDouble(s);
int i = (int) d;This approach first parses the string as a double type, then converts it to int through explicit casting. During this conversion, Java performs rounding toward zero by truncating the fractional part.
Type Conversion Behavior
When converting double or float to int, Java removes all digits after the decimal point:
int i = (int) 0.9999; // Result is 0
int j = (int) 3.14; // Result is 3
int k = (int) -2.7; // Result is -2This truncation behavior may cause precision loss in certain application scenarios, requiring developers to decide whether to accept such conversion based on specific requirements.
Alternative Methods Comparison
Beyond basic type casting, the intValue() method of the Double class can also be used:
String s = "0.01";
int i = new Double(s).intValue();However, this method creates additional Double objects and may be less efficient than direct type casting in performance-sensitive scenarios.
Best Practices Recommendations
When selecting numerical parsing methods, consider the following factors: use Integer.parseInt() if the string definitively represents an integer; use Double.parseDouble() or Float.parseFloat() if it contains fractional components. During type conversion, clearly understand how truncation behavior affects computational results, and employ rounding or other strategies when necessary.