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: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 :
as converting from a floating value to an int will drop any decimal without rounding.