0

I have following test code snippet, which has a float type variable f, and I have assigned the value 3627.299685 to it. After that, I am creating one more variable d2 of type double, by typecasting f to double.

Printing the values of both f and d2, my observation results are bit weird, as both the variable values do not match exactly the value assigned to the variable.

Is it limitation of the Java 1.7.0_97, 64Bit server? Or is there any other way, we can print the exact value of the variable here?

public class TestFloat  {

   public static void main(String[] args) {
      float f = 3627.299685f;
      double d2 = (double)f;
      System.out.println("Float:" + f);
      System.out.println("Float converted to Double:" + d2);
   }
}

user@test01:/tmp$ java TestFloat
Float:3627.2998
Float converted to Double:3627.2998046875
khelwood
  • 55,782
  • 14
  • 81
  • 108
Pert8S
  • 582
  • 3
  • 6
  • 21
  • it is not possible to have exact representation for every possible float and double – Scary Wombat May 23 '17 at 08:08
  • "as both the variable values, doest not matches exactly with the value assigned to the variable" - well that isn't much of a surprise, given that you've assigned a value with 10 significant decimal digits to a value of a type that only has 8-9 digits of precision... – Jon Skeet May 23 '17 at 08:11
  • The value printed for `d2` is actually the precise value of both the `float` and the `double`. – Jon Skeet May 23 '17 at 08:12
  • The double and float are equal to each other. The printed float value is rounded to less precision because it is a less precise data type. – khelwood May 23 '17 at 08:19

0 Answers0