Convert Double to Integer in Java
Given a Double real number. Write a Java program to convert the given double number into an Integer (int) in Java.
Input: double = 3452.234 Output: 3452 Input: double = 98.23 Output: 98
Double: The double data type is a double-precision 64-bit IEEE 754 floating-point. Its value range is endless. The double data type is commonly used for decimal values, just like float. The double data type also should never be used for precise values, such as currency. Its default value is 0.0.
Example: double d1 = 10.5
Integer: The Integer or int data type is a 32-bit signed two’s complement integer. Its value-range lies between – 2,147,483,648 (-2^31) to 2,147,483,647 (2^31 -1) (inclusive). Its minimum value is – 2,147,483,648 and maximum value is 2,147,483,647. Its default value is 0. The int data type is generally used as a default data type for integral values unless if there is no problem about memory.
Example: int a = 10
There are numerous approaches to do the conversion of Double datatype to Integer (int) datatype. A few of them are listed below.
- Using TypeCasting
- Using Double.intValue() method
- Using Math.round() method
Approach 1: Using TypeCasting
This technique is very simple and user-friendly.
double data = 3452.345 int value = (int)data;
Double - 3452.345 Integer - 3452
Approach 2: Using Double.intValue() method
This technique is similar to typecasting method. The main difference between typecasting method and this method is that typecasting method is an explicit method, and this method is a Wrapper class Double truncates all digits after the decimal point.
double data = 3452.345 Double newData = new Double(data); int value = newData.intValue();
Double - 3452.345 Double - 3452
Approach 3: Using Math.round() method
Math.round() accepts a double value and converts it into the nearest long value by adding 0.5 to the value and trimming its decimal points. The long value can then be converted to an int using typecasting.
long Math.Round(Double doubleValue);
Double : 3452.345 Integer : 3452 Double : 3452.765 Integer : 3453
Note: Here you can see that the Math.round() method converts the double to an integer by rounding off the number to the nearest integer.
For example – 10.6 will be converted to 11 using Math.round() method and 1ill be converted to 10 using typecasting or Double.intValue() method.