Mehman Bashirov Mehman Bashirov - 1 year ago 83
Java Question

Why do i get a NumberFormatException

The below code. Why do i get a NumberFormatException

public static void main(String[] args) {
Float f = null;
try {
f = Float.valueOf("12.3");
String s = f.toString();
int i = Integer.parseInt(s);
System.out.println("i = " + i);
} catch (Exception e) {
System.out.println("trouble : " + f + e);

Answer Source

The problem is when you call "Integer.parseInt(s)", the method believe you have integer content in there and it will convert the string into the int. But now you have float value there. So it cannot convert into integer from string(that contain floating point value) by Integer.parseInt() method. What you can do is

 float fl = Float.parseFloat(s);

 int i = (int) f1;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download