Originally posted by Sheetal Kaul:
ok, then it should apply for the double also, but if am declaring the value as double d = 1.2d then it is printing 1.2 only, why not 1.2000000476837158 as it is printing if am declaring the double d = 1.2f
Because double can express 1.2 more precisely than float. 1.2f is a rough approximation that's good enough for
float f1 = 1.2f;
System.out.println(f1); // Output: 1.2
But when you assign 1.2f to a double variable, the imprecision of 1.2f becomes apparent when you print the result with double precision.
double d1 = 1.2f;
System.out.println(d1); // Output: 1.2000000476837158
When you use 1.2d it's still an approximation, but it's a closer approximation.
If you don't understand why the computer can't store the value 1.2 perfectly, get out a calculator and try figuring out how 1.2 would be expressed in base-2 (which is binary, the way the computer stores the number).
I only calculated 8 digits past the radix point, giving me
1.00110011...
which is 1.19921875 in base-ten (decimal). If you keep going, you'll gradually get closer to 1.2 but I doubt that you'll ever hit it. Eventually you'll have more binary digits than a double has room for. Remember that double has more digits or precision than float, but it's still finite.