how can I parse "30.0" or "30.00" to Integer?

Here's how you do it:

String str = "300.0";
System.out.println((int) Double.parseDouble(str));

The reason you got a NumberFormatException is simply that the string ("300.00", which is a floating point number) could not be parsed as an integer.


It may be worth mentioning, that this solution prints 300 even for input "300.99". To get a proper rounding, you could do

System.out.println(Math.round(Double.parseDouble("300.99")));  // prints 301

I am amazed no one has mentioned BigDecimal.

It's really the best way to convert string of decimal's to int.
Josuha Bloch suggest using this method in one of his puzzlers.

Here is the example run on Ideone.com

class Test {
  public static void main(String args[]) {
    try {
        java.math.BigDecimal v1 = new java.math.BigDecimal("30.0");
        java.math.BigDecimal v2 = new java.math.BigDecimal("30.00");            
      System.out.println("V1: " + v1.intValue() + " V2: " + v2.intValue());
    } catch(NumberFormatException npe) {
      System.err.println("Wrong format on number");
    }
  }
}

You should parse it to double first and then cast it to int:

String str="300.0";
System.out.println((int)(Double.parseDouble(str)));

You need to catch NumberFormatExceptions though.

Edit: thanks to Joachim Sauer for the correction.

Tags:

Java