When can a double-type be preferred over float-type in Java?


Both double-type and float-type can be used to represent floating-point numbers in Java. A double-type is preferred over float-type if the more precise and accurate result is required. The precision of double-type is up to 15 to 16 decimal points while the precision of float type is only around 6 to 7 decimal digits.

The double-type can be used for all the calculations and temp variables while a float-type can be used to maintain an array of numbers. A double-type uses 1 bit for a sign and 11 bits for exponent while float-type only uses 1 bit for a sign and 8 bits for exponent. The default value of double-type is 0.0d while default value of float-type is 0.0f.

Example

public class DoubleFloatTest {
   public static void main(String []args) {
      double d = 55.637848675695785;
      float f = 25.657933f;
      System.out.println("Value of double: " + d);
      System.out.println("Value of float: " + f);
   }
}

Output

Value of double: 55.637848675695786
Value of float: 25.657932 

Updated on: 01-Dec-2023

179 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements