views:

416

answers:

4

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?

+6  A: 

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

Joren
+5  A: 
String s = "0.01";
double d = Double.parseDouble(s);
int i = (int) d;

The reason for the exception is that an integer isn't decimal.
A double or a float are a decimal numbers. An int not. You have to know by yourself what you need.

The way Java cast an double to a int: remove the decimal piece.

int i = (int) 0.99d;

i will by zero.

Martijn Courteaux
Your cast will completely lose the fractional information. I'm not sure that's a good idea to advise.
Joren
Ok! maybe I will have to do something like this Double d = Double.parseDouble(s); right?
Kevin Boyd
@Joren: I know but he wants an Integer (if I check his code)
Martijn Courteaux
@Kevin: yes, but you can use also 'double' instead of 'Double'
Martijn Courteaux
He says he wants an integer, but are we sure that's what he *needs*?
Joren
+1  A: 

Use Double.parseDouble(String a) what you are looking for is not an integer as it is not a whole number.

denis
A: 

Use,

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