Convert double to Int, rounded down

JavaType ConversionRounding

Java Problem Overview


How to convert a double value to int doing the following:

Double If x = 4.97542. Convert to int x = 4.

Double If x = 4.23544. Convert to int x = 4.

That is, the answer is always rounding down.

Java Solutions


Solution 1 - Java

If you explicitly cast double to int, the decimal part will be truncated. For example:

int x = (int) 4.97542;   //gives 4 only
int x = (int) 4.23544;   //gives 4 only

Moreover, you may also use Math.floor() method to round values in case you want double value in return.

Solution 2 - Java

If the double is a Double with capital D (a boxed primitive value):

Double d = 4.97542;
int i = (int) d.doubleValue();

// or directly:
int i2 = d.intValue();

If the double is already a primitive double, then you simply cast it:

double d = 4.97542;
int i = (int) d;

Solution 3 - Java

double myDouble = 420.5;
//Type cast double to int
int i = (int)myDouble;
System.out.println(i);

The double value is 420.5 and the application prints out the integer value of 420

Solution 4 - Java

Another option either using Double or double is use Double.valueOf(double d).intValue();. Simple and clean

Solution 5 - Java

I think I had a better output, especially for a double datatype sorting.

Though this question has been marked answered, perhaps this will help someone else;

Arrays.sort(newTag, new Comparator<String[]>() {
         @Override
         public int compare(final String[] entry1, final String[] entry2) {
              final Integer time1 = (int)Integer.valueOf((int) Double.parseDouble(entry1[2]));
              final Integer time2 = (int)Integer.valueOf((int) Double.parseDouble(entry2[2]));
              return time1.compareTo(time2);
         }
    });

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionVogatsuView Question on Stackoverflow
Solution 1 - JavawaqaslamView Answer on Stackoverflow
Solution 2 - JavaNatixView Answer on Stackoverflow
Solution 3 - JavaHabibView Answer on Stackoverflow
Solution 4 - JavaJoao EvangelistaView Answer on Stackoverflow
Solution 5 - JavaHexxonDivView Answer on Stackoverflow