Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

I using:

String str="300.0";
System.out.println(Integer.parseInt(str));

return an exception:

Exception in thread "main" java.lang.NumberFormatException: For input string: "300.0"

How can I parse this String to int?

thanks for help :)

like image 556
Koerr Avatar asked Feb 01 '11 09:02

Koerr


People also ask

What does parsing an integer mean?

Parsing is to read the value of one object to convert it to another type. For example you may have a string with a value of "10". Internally that string contains the Unicode characters '1' and '0' not the actual number 10. The method Integer. parseInt takes that string value and returns a real number.

Can we convert string to integer?

The method generally used to convert String to Integer in Java is parseInt() of String class.

What is NumberFormatException in parseInt?

The NumberFormatException is an unchecked exception in Java that occurs when an attempt is made to convert a string with an incorrect format to a numeric value. Therefore, this exception is thrown when it is not possible to convert a string to a numeric type (e.g. int, float).


2 Answers

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
like image 114
aioobe Avatar answered Nov 02 '22 04:11

aioobe


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");
    }
  }
}
like image 26
Shervin Asgari Avatar answered Nov 02 '22 03:11

Shervin Asgari