3

Why the first statement return true, and the second return false, isn´t it supposed to be equal, what can i do to bypass this program, i really need this

System.out.println(0.99951f == 0.9995f); //true
System.out.println(0.999f + 0.0005 == 0.9995f); //false
Mateus Martins
  • 442
  • 3
  • 16
  • What do you *actually* want to achieve? Comparing floats with `==` is generally a dangerous idea. – luk2302 Mar 12 '19 at 18:55
  • Take a look at [IEEE-754 Floating Point Converter](https://www.h-schmidt.net/FloatConverter/IEEE754.html). It will show you the exact representation, which also explains your observation. – Zabuzard Mar 12 '19 at 18:56
  • i did´nt knew it, why is it a bad idea?? @luk2302 – Mateus Martins Mar 12 '19 at 18:56
  • 1
    Well, look at your question, that is why it is dangerous, because it does not behave as *you* expect. – luk2302 Mar 12 '19 at 18:57
  • 1
    @MateusMartins Use BigDecimal for that. – LppEdd Mar 12 '19 at 18:58
  • 1
    Comparison of floating points should, because of that, always be done by using a delta. I.e. by allowing a certain, small, difference. `Math.abs(first, second) < delta`, or similar (can be more sophisticated, such as percentage difference). – Zabuzard Mar 12 '19 at 18:58
  • 3
    You are not actually comparing two floating point values in your second case. You are adding `0.0005`, which is a `double`, so the whole expression becomes `double`, and it's not necessarily the same double that the right-hand value will be converted into. – RealSkeptic Mar 12 '19 at 19:06
  • @RealSkeptic That seems like an answer to me. – Dawood ibn Kareem Mar 12 '19 at 19:09

0 Answers0