54

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.

Sheldon
  • 1,197
  • 1
  • 15
  • 29
Vogatsu
  • 571
  • 1
  • 5
  • 8

5 Answers5

106

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.

Code-Apprentice
  • 76,639
  • 19
  • 130
  • 241
waqaslam
  • 66,380
  • 16
  • 161
  • 174
  • What does it mean to "loose decimal values"? Does it give the same numbers as calling `Math.floor()`? – Samuel Edwin Ward Dec 27 '15 at 00:17
  • A Double is not an Integer, so the cast won't work. Note the difference between the Double class and the double primitive. Also note that a Double is a Number, so it has the method intValue, which you can use to get the value as a primitive int. If you try to cast Double to int you will get a casting exception: java.lang.ClassCastException: java.lang.Double cannot be cast to java.lang.Integer – Ali Rad Feb 28 '19 at 14:22
31

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;
Natix
  • 13,626
  • 7
  • 53
  • 68
5
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

Habib
  • 212,447
  • 27
  • 392
  • 421
3

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

Joao Evangelista
  • 2,299
  • 2
  • 25
  • 36
0

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);
         }
    });
gvlasov
  • 16,604
  • 19
  • 65
  • 103
HexxonDiv
  • 13
  • 1
  • 7