-1

This is the code

    public static void main(String[] args) {
      double x=5.6556464566546546546556465465465;
      float y=(float)x;
      double z=  1+y;
        System.out.println(x+"\n"+y+"\n"+z);
    }
}

and this is the output

5.6556464566546545
5.6556463
6.655646324157715

I can understand the value of x and y but z from where it got those fractional numbers after the 3??!

Thank you very much

Rami
  • 1
  • 3
    The issue has a thorough discussion at https://stackoverflow.com/questions/17504833/why-converting-from-float-to-double-changes-the-value. Hopefully it will answer your question. – Kasalwe Aug 17 '20 at 19:35
  • 4
    you defined a double precision floating point and then cast it as single precision. that meant the extra precision got discarded. nothing weird here. – Nathan Hughes Aug 17 '20 at 19:38
  • See also: [Is Floating Point Math Broken?](https://stackoverflow.com/questions/588004/is-floating-point-math-broken). – andrewJames Aug 17 '20 at 19:45

1 Answers1

1

Floats are an approximation of the actual number in Java, due to the way they're stored. If you need exact values, use a BigDecimal instead.

Roman Shtykalo
  • 185
  • 1
  • 5