Sunday, November 9, 2008

Published 11/09/2008 by with 2 comments

possible loss of precision

You may see the error message 'possible loss of precision' for any of the following reasons:

1) You are trying to assign a fractional number into a float variable(why not?). Actually Java compiler considers the fractional number as double by default. You need to explicitly specify the fractional number as float by giving the character 'f' or 'F' after the the number, like float number = 65.37F;

2) Or you are trying to assign the value of a double variable into a float variable. Memory size of double is 8 byte and that of float is 4 byte. If you assign a double value into a float value data may be lost. So be sure about the data type. If you are sure you want to assign the double into float, you need to cast it appropriately, like float floatVariable = (float)doubleVariable;

An example is given below:

public class PossibleLossOfPrecision
{
public static void main(String args[])
{

float floatNumber1=65.37; // error
double doubleNumber=65.37;
float floatNumber2=doubleNumber; // error

System.out.println(floatNumber1);
System.out.println(doubleNumber);
System.out.println(floatNumber2);

}
}


The above code is wrong; write this code as below and the problem will be solved.

public class PossibleLossOfPrecisionSolution
{
public static void main(String args[])
{

float floatNumber1=65.37F; // error solved
double doubleNumber=65.37;
float floatNumber2=(float)doubleNumber; // error solved

System.out.println(floatNumber1);
System.out.println(doubleNumber);
System.out.println(floatNumber2);

}
}
    email this       edit

2 comments: