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 ; 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 ); this can be done using the Math.round() function in Java.
Since double is a bigger data type than int, it needs to be down-casted. See the syntax below:
int IntValue = (int) DoubleValue;
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);}}
Math.round()Math.round() accepts a double value and converts it into the nearest long value by adding 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);}}
Free Resources