How can I parse "30.0" or "30.00" on Integer?

I use:

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

returns an exception:

Exception in thread "main" java.lang.NumberFormatException: for input line: "300.0"

How can I parse this string for int?

thanks for the help:)

+7
source share
5 answers

Here's how you do it:

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

( demo of ideone.com )

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


It may be worth noting that this solution prints 300 even for entering "300.99" . To get the correct rounding , you could do

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

I am amazed that no one mentioned BigDecimal .

This is really the best way to convert a decimal string to int.
Hosuha Bloch suggests using this method in one of her puzzles.

Here is an 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"); } } } 
+3
source

First you have to parse it to double , and then apply it to int :

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

You need to catch a NumberFormatException .

Edit: Thanks to Joachim Sauer for the correction.

+2
source

You can use the Double.parseDouble () method to be the first to apply it to double , and then translate double into int by putting (int) in front of it. Then you will get the following code:

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

Integer.parseInt() has to take a string that is an integer (i.e. does not have decimal points, even if the number is equivalent to an integer. The exception you get there essentially says β€œyou”, ve told me that this number is an integer, but this string is not in a valid format for an integer! "

If the number contains a decimal component, you need to use Double.parseDouble() , which will return a double primitive. However, since you are not interested in the decimal component, you can safely abandon it by simply translating double into int:

 int num = (int)Double.parseDouble(str); 

Note, however, that this will simply lower the decimal component; it will not round the number. So casting 1.2, 1.8, or 1.999999 to int will give you 1. If you want to round the number that is returned, use Math.round () instead of just clicking on int.

+1
source

All Articles