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.
Java - parseInt() Method This method is used to get the primitive data type of a certain String. parseXxx() is a static method and can have one argument or two.
The parseDouble() method of Java Double class is a built in method in Java that returns a new double initialized to the value represented by the specified String, as done by the valueOf method of class Double. Parameters: It accepts a single mandatory parameter s which specifies the string to be parsed.
Conversion using valueOf() method of Double wrapper class Double wrapper class valueOf() method converts int value to double type. It returns the Double-object initialized with the provided integer value. Here, d = variable to store double value after conversion to double data type.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With