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

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?


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.


0.01 is not an integer (whole number), so you of course can't parse it as one. Use Double.parseDouble or Float.parseFloat instead.


Use,

String s="0.01";
int i= new Double(s).intValue();