How to do an Integer.parseInt() for a decimal number?

Kevin Boyd picture Kevin Boyd · Sep 20, 2009 · Viewed 202.9k times · Source

The Java code is as follows:

String s = "0.01";
int i = Integer.parseInt(s);

However this is throwing a NumberFormatException... What could be going wrong?

Answer

Martijn Courteaux picture Martijn Courteaux · Sep 20, 2009
String s = "0.01";
double d = Double.parseDouble(s);
int i = (int) d;

The reason for the exception is that an integer does not hold rational numbers (= basically fractions). So, trying to parse 0.3 to a int is nonsense. A double or a float datatype can hold rational numbers.

The way Java casts a double to an int is done by removing the part after the decimal separator by rounding towards zero.

int i = (int) 0.9999;

i will be zero.