-1

Quick question, What is the best way to convert an primitive data type double to a primitive data type int. Currently I am using the following code but it seems to be a lot of methods to do a simple task.

double i = 2.0;
int i2 = Integer.parseInt(Double.toString(i));
Jdman216
  • 55
  • 1
  • 10

4 Answers4

6

just cast double to (int)

double i = 2.0;
int i2 =  (int) i;
Nambi
  • 11,944
  • 3
  • 37
  • 49
2

You could either cast the double to an int:

double i = 2.0
int i2 = (int) i;

or, you could round the number to the nearest whole number, then cast it to an int, just in case you would like to round:

double i = 2.2
int i2 = (int) Math.round(i);

or, you could use

double i = 2.0
int i2 = Integer.parseInt(String.valueOf(i));

About best, though, the first option would be best for the least code, and the second would be better if you would like to get the closest integer to the double.

Jojodmo
  • 23,357
  • 13
  • 65
  • 107
  • 1
    You also need to cast the second one... – Bernhard Barker Feb 02 '14 at 03:05
  • 1
    @Dukeling I actually thought that to, so I tried using `int i = Math.round(2.2)` in eclipse and it turns out you don't need to cast it. – Jojodmo Feb 02 '14 at 03:06
  • 2
    Because in that case it treats `2.2` as a `float`. Try it with the `double` declaration as in your answer. – Bernhard Barker Feb 02 '14 at 03:08
  • 2
    @Dukeling Ah, when rounding a `float` you will get an `int`, and when rounding a `double` you will get a `long`. Updated answer. – Jojodmo Feb 02 '14 at 03:10
  • 1
    An alternative is to use a float (2.2f), which will work without the need to cast. – Makoto Feb 02 '14 at 03:11
  • @Makoto True, yet this would not work if you're doing something like `double d = 2.2;`, `int i = Math.round(d);`, due to the fact that you can't use float literal in a variable (Even though I think you should be able to do `Math.round((d)f);`. – Jojodmo Feb 02 '14 at 03:21
  • The 3rd suggestion throws a `java.lang.NumberFormatException` – BaSsGaz Nov 12 '16 at 14:22
1

You can turn any object from one compatible type to another by using 'type-casting'. You use this syntax:

double i = 2.0;
int i2 =  (int) i;

Notice how I just put (int) before the variable i? This basically says 'hey, try to make i an int, if you can'. Since java can easily convert a float to an int, it will.

Damien Black
  • 5,579
  • 18
  • 24
1

Also you can use Math.floor().

public class Example {
    public static void main(String args[]) { 
        double i = 2.9;

        System.out.println((int)(i));
        System.out.println((int)Math.floor(i));
        System.out.println((int)(-i));
        System.out.println((int)Math.floor(-i));        
    }
}

output:

2
2
-2
-3
Pshemo
  • 122,468
  • 25
  • 185
  • 269