Mehman Bashirov Mehman Bashirov - 2 months ago 5x
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);


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;