class Main {
public static void main(String[] args) {
// create double variables
double a = 23.78D;
double b = 52.11D;
// convert double into int
// using typecasting
int c = (int)a;
int d = (int)b;
System.out.println(c); // 23
System.out.println(d); // 52
}
}
23
52
double
type variables a
and b
. Notice the line,int c = (int)a;​
Here, the higher data type double
is converted into a lower data type int
. Hence, we need to explicitly use int
inside the bracket.double
type variable into int using the Math.round()
method. For example,class Main {
public static void main(String[] args) {
// create double variables
double a = 99.99D;
double b = 52.11D;
// convert double into int
// using typecasting
int c = (int)Math.round(a);
int d = (int)Math.round(b);
System.out.println(c); // 100
System.out.println(d); // 52
}
}
100
52
a
and b
. Notice the line,int c = (int)Math.round(a);​
Here,decimal
value into long
valuelong
value into int
using typecastingMath.round()
method rounds the decimal
value to the closest long
value.