Trusted answers to developer questions

How to convert a double to int in Java

Get Started With Data Science

Learn the fundamentals of Data Science with this free course. Future-proof your career by adding Data Science skills to your toolkit — or prepare to land a job in AI, Machine Learning, or Data Analysis.

Let’s say that the double variable x holds the value 3.6987 and needs to be converted to an int. There are two ways that this can be done:

  • All the digits after the decimal are lost and x holds the integer 33; this can be done using typecasting in Java.

  • The value is rounded off to the nearest integer (i.e.,3.6987 is rounded off to 44); this can be done using the Math.round() function in Java.​

svg viewer

1. Typecasting

Since double is a bigger data type than int, it needs to be down-casted. See the syntax below:

int IntValue = (int) DoubleValue;

Code

The code snippet below illustrates double to int typecasting in Java:

class DoubleToInt {
public static void main( String args[] ) {
double DoubleValue = 3.6987;
int IntValue = (int) DoubleValue;
System.out.println(DoubleValue + " is now " + IntValue);
}
}

2. Using Math.round()

Math.round() accepts a double value and converts it into the nearest long value by adding 0.50.5 to the value and truncating its decimal points. The long value can then be converted to an int using typecasting.

The syntax for the Math.round() function is:

long Math.round(double DoubleValue);

The code snippet below illustrates the usage of Math.round() when converting a double data type to an int in Java:

class DoubleToInt {
public static void main( String args[] ) {
double DoubleValue = 3.6987;
int IntValue = (int) Math.round(DoubleValue);
System.out.println(DoubleValue + " is now " + IntValue);
}
}

RELATED TAGS

convert
double
int
java
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?