Tuesday, 30 April 2013

Java float and double Variables

If you have a number with digits to the right of the decimal point, you can store it in a float or a double variable. However, if you try to assign it directly, it doesn't work:

UBUNTU > cat prog12.java
public class prog12
{
public static void main (String args[])
  {
  float f1 = 1/5;
  double d1 = 1/5;
  System.out.println ("f1 = " + f1);
  System.out.println ("d1 = " + d1);
  }
}
UBUNTU > javac prog12.java
UBUNTU > java prog12
f1 = 0.0
d1 = 0.0
UBUNTU > 


You can add an f (or F) at the end of the number before assigning it to a float variable and you can add a d (or D) at the end before assigning it to a double. Notice how the double has greater precision:

UBUNTU > cat prog13.java
public class prog13
{
public static void main (String args[])
  {
  float f2 = 1/7f;
  double d2 = 1/7d;
  System.out.println ("f2 = " + f2);
  System.out.println ("d2 = " + d2);
  f2 = 1/9F;
  d2 = 1/9D;
  System.out.println ("f2 = " + f2);
  System.out.println ("d2 = " + d2);
  }
}
UBUNTU > javac prog13.java
UBUNTU > java prog13
f2 = 0.14285715
d2 = 0.14285714285714285
f2 = 0.11111111
d2 = 0.1111111111111111
UBUNTU >

Alternatively, you can add (float) before a float variable or (double) before a double. This is called casting:

UBUNTU > cat prog14.java
public class prog14
{
public static void main (String args[])
  {
  float f3 = (float) 1/13;
  double d3 = (double) 1/13;
  System.out.println ("f3 = " + f3);
  System.out.println ("d3 = " + d3);
  }
}
UBUNTU > javac prog14.java
UBUNTU > java prog14
f3 = 0.07692308
d3 = 0.07692307692307693
UBUNTU >

As well as giving greater precision, a double can also store much larger numbers than a float:

UBUNTU > cat prog15.java
public class prog15
{
public static void main (String args[])
  {
  System.out.println
  ("Largest float = " + Float.MAX_VALUE);
  System.out.println
  ("Largest double = " + Double.MAX_VALUE);
  }
}
UBUNTU > javac prog15.java
UBUNTU > java prog15
Largest float = 3.4028235E38
Largest double = 1.7976931348623157E308
UBUNTU >

If you have a Java book on Amazon, which you would like to advertise here for free, please write to me at international_dba@yahoo.co.uk.