My program receives some input (a String
). It is rather possible that the input is in the form of a double
, like "1.5"
. But I would like to convert it to an integer
, so I can end up with just a 1
.
First, I tried this:
Integer.parseInt(someString);
But it doesn't work - I'm assuming it is because of the dot .
that it can't parse it.
So I thought that maybe the Integer
class can create an integer
from a double
. So I decided to create a double
and then make it an int
, like this:
Integer.parseInt(Double.parseDouble(someString));
But apparently there is
no suitable method found for parseInt(double)
So, what do you suggest? Are there one-liners for this? I thought about making a method that removes the dot and all characters after it... but that doesn't sound very cool.
It is safe to parse any numbers as double
, then convert it to another type after. Like this:
// someString = "1.5";
double val = Double.parseDouble(someString); // -> val = 1.5;
int intVal = (int) Math.floor(val); // -> intVal = 1;
Note that with Java 7 (not tested with earlier JVM, but I think it should work too), this will also yield the same result as above :
int intVal = (int) Double.parseDouble(someString);
as converting from a floating value to an int will drop any decimal without rounding.
use casting.
double val = Double.parseDouble(someString);
int intVal = (int) Math.floor(val);
You've got the Double
, I assume, with Double.parseDouble
. So just use:
int i = (int) Double.parseDouble(someString);
尝试,
int no= new Double(string).intValue();
Try this:
1) Parse the string as double 2) cast from double to int
public static void main(String[] args) {
String str = "123.32";
int i = (int) Math.floor(Double.parseDouble(str));
System.out.println(i);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.