In this tutorial, you will learn how to convert double to int in Java. A double number contains decimal digits so when we convert it into an int, the decimal digits are truncated. We can however use certain approaches where we can convert it into a nearest int rather than truncating decimal digits. Let’s see the most common methods:
1. Type Casting
Type casting is the easiest method for double to int conversion. It truncates the decimal part and keeps the integer part. If you only care about the integer part then this is the simplest solution.
double myDouble = 9.99;
int myInt = (int) myDouble;
System.out.println(myInt); // Output: 9
2. Using Math.round()
If you want the nearest integer as output, you can use Math.round()
method. This method returns a long value so you need to cast it to convert it into an int.
double myDouble = 9.99;
int myInt = (int) Math.round(myDouble);
System.out.println(myInt); // Output: 10
3. Using Math.floor() and Math.ceil()
You can use Math.floor()
or Math.ceil()
method to round down or up the result respectively. These methods return a double value so you need to cast the returned value.
double myDouble = 9.99;
int myIntDown = (int) Math.floor(myDouble); //round down
int myIntUp = (int) Math.ceil(myDouble); // round up
System.out.println(myIntDown); // Output: 9
System.out.println(myIntUp); // Output: 10
4. Using Double.intValue()
This method works similar to the Type casting method. It truncates the decimal part and returns the integer part.
Double myDouble = 9.99;
int myInt = myDouble.intValue();
System.out.println(myInt); // Output: 9
Java Program for double to int Conversion
In this program, we will see the discussed methods:
public class Main {
public static void main(String[] args) {
double myDouble = 9.99;
// 1. Type Casting
int myInt1 = (int) myDouble;
System.out.println("Type Casting: " + myInt1);
// 2. Conversion using Math.round()
int myInt2 = (int) Math.round(myDouble);
System.out.println("Math.round(): " + myInt2);
// 3. Round down/up using Math.floor() and Math.ceil()
int myInt3 = (int) Math.floor(myDouble);
int myInt4 = (int) Math.ceil(myDouble);
System.out.println("Math.floor(): " + myInt3);
System.out.println("Math.ceil(): " + myInt4);
// 4. Conversion using Double.intValue()
Double myDoubleObject = myDouble;
int myInt5 = myDoubleObject.intValue();
System.out.println("Double.intValue(): " + myInt5);
}
}
Output:
Type Casting: 9
Math.round(): 10
Math.floor(): 9
Math.ceil(): 10
Double.intValue(): 9
Recommended Posts:
Leave a Reply