-3

I am getting number format exception, not sure what I am doing wrong.

public static void main(String[] args) {

    int v = 1476423;
    double d = v;
    System.out.println("Double "+v);
    String s = String.valueOf(d);
    System.out.println("String "+s);
    v = Integer.parseInt(s);
    System.out.println("Integer "+v);
}

When I am trying to print v, it is giving number format exception. Can somebody help here?

Error:

Double 1476423
String 1476423.0
Exception in thread "main" java.lang.NumberFormatException: For input string: "1476423.0"
    at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
    at java.lang.Integer.parseInt(Integer.java:580)
    at java.lang.Integer.parseInt(Integer.java:615)
    at testCases.Random.main(Random.java:12)
DisplayName
  • 222
  • 1
  • 2
  • 11

2 Answers2

2

This is clearly not an integer value, it has a decimal part, even though it's zero:

"1476423.0"

Either do this:

int v = Integer.parseInt("1476423");

Or this:

double d = Double.parseDouble("1476423.0");
Óscar López
  • 232,561
  • 37
  • 312
  • 386
0

You can fix the problem by deleting this line

v = Integer.parseInt(s);

But the problem is that double d = v; makes v a floating point number, which you convert to a string, then try to convert back to an int, which is not very clear why you do that because you aren't changing the value of v in any way.

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
  • i was just trying other stuff, actually the problem is I am getting a `string` with a `.` so I wanted to convert it into `int` and remove the `.0` – DisplayName Jun 08 '16 at 06:01
  • Yes, a string representation of a floating point number (in other words, a decimal) cannot be parsed to an int because integers do not contain decimals – OneCricketeer Jun 08 '16 at 06:02