[java] Convert double to Int, rounded down

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.

This question is related to java type-conversion rounding

The answer is


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


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;

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


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);
         }
    });

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to type-conversion

How can I convert a char to int in Java? pandas dataframe convert column type to string or categorical How to convert an Object {} to an Array [] of key-value pairs in JavaScript convert string to number node.js Ruby: How to convert a string to boolean Convert bytes to int? Convert dataframe column to 1 or 0 for "true"/"false" values and assign to dataframe SQL Server: Error converting data type nvarchar to numeric How do I convert a Python 3 byte-string variable into a regular string? Leading zeros for Int in Swift

Examples related to rounding

How to round a numpy array? How to pad a string with leading zeros in Python 3 Python - round up to the nearest ten How to round a Double to the nearest Int in swift? Using Math.round to round to one decimal place? How to round to 2 decimals with Python? Rounding to 2 decimal places in SQL Rounding to two decimal places in Python 2.7? Round a floating-point number down to the nearest integer? Rounding BigDecimal to *always* have two decimal places