Convert Double to Integer in Java
Given a Double real number, the task is to convert it into Integer in Java.
Examples:
Input: double = 3452.234 Output: 3452 Input: double = 98.23 Output: 98
- Using typecasting: This technique is a very simple and user friendly.
Syntax:
double data = 3452.345 int value = (int)data;
Example:
// Java program to convert Double to int
// using Typecasting
public
class
GFG {
// main method
public
static
void
main(String args[])
{
// Get the double value
double
data =
3452.345
;
// convert into int
int
value = (
int
)data;
// print the int value
System.out.println(value);
}
}
Output:
3452
- Using Math.round(): This method returns the nearest integer.
Syntax:
double data = 3452.645 int value = (int)Math.round(data);
Example:
// Java program to convert Double to int
// using Math.round()
public
class
GFG {
// main method
public
static
void
main(String args[])
{
// Get the double value
double
data =
3452.345
;
// convert into int
int
value = (
int
)Math.round(data);
// print the int value
System.out.println(value);
}
}
Output:3452
- Using Double.intValue(): This technique is similar to typecasting method. Wrapper class Double truncates all digits after decimal point.
Syntax:
double data = 3452.345 Double newData = new Double(data); int value = newData.intValue();
Example:
// Java program to convert Double to int
// using using Double.intValue()
public
class
GFG {
// main method
public
static
void
main(String args[])
{
// Get the double value
double
data =
3452.345
;
// Create a wrapper around
// the double value
Double newData =
new
Double(data);
// convert into int
int
value = newData.intValue();
// print the int value
System.out.println(value);
}
}
Output:3452
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.