Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use parseInt for a double?

Tags:

java

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.

like image 863
Voldemort Avatar asked Sep 24 '12 01:09

Voldemort


People also ask

When parseInt () method can be used?

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.

How does parse double work?

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.

How do you convert an int to a double?

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.


1 Answers

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.

like image 120
Yanick Rochon Avatar answered Oct 23 '22 06:10

Yanick Rochon