How can I use parseInt for a double?

My program receives some input (a String ). It is possible that the input has the form double , for example, "1.5" . But I would like to convert it to integer , so I can only get 1 .

First, I tried this:

 Integer.parseInt(someString); 

But that will not work - I guess because of the point . he cannot take it apart.

So I thought that maybe the integer class could create an integer from double . So I decided to create a double and then make it int , for example:

 Integer.parseInt(Double.parseDouble(someString)); 

But apparently there is

No suitable method found for parseInt (double)

So what do you suggest? Is there one line for this? I was thinking of creating a method that removes the dot and all the characters after it ... but that doesn't sound very cool.

+7
source share
5 answers

It is safe to parse any numbers as double , and then convert them to another type. Like this:

 // someString = "1.5"; double val = Double.parseDouble(someString); // -> val = 1.5; int intVal = (int) Math.floor(val); // -> intVal = 1; 

Please note that with Java 7 (not tested with an earlier JVM, but I think it should work too), this will also give the same result as above:

 int intVal = (int) Double.parseDouble(someString); 

since converting from a floating value to int will discard any decimal place without rounding.

+7
source

use casting.

 double val = Double.parseDouble(someString); int intVal = (int) Math.floor(val); 
+4
source

You have Double , I suppose, with Double.parseDouble . So just use:

 int i = (int) Double.parseDouble(someString); 
+2
source

Try

 int no= new Double(string).intValue(); 
+1
source

Try the following:

1) Parse the string as double 2) from two to int

 public static void main(String[] args) { String str = "123.32"; int i = (int) Math.floor(Double.parseDouble(str)); System.out.println(i); } 
+1
source

All Articles