I understand that it's not correct to compare two doubles using ==
operator. But is it safe to compare two doubles like <=
or >=
?
Asked
Active
Viewed 87 times
0

llswdon
- 45
- 5
-
The correct way to compare doubles and floats in Java : https://howtodoinjava.com/java-examples/correctly-compare-float-double/ – Yassir Khaldi Oct 13 '21 at 10:43
1 Answers
-2
Actually it depends on your need. Of course ==
operator is not at all safe with double
data type. But using operators like <=
and >=
might not suit your need. So instead, you can convert double into float data type and then check. I know that it will not provide you precision but that's the way you have to do.
Those wondering why ==
is not safe, try out
System.out.println(0.1 + 0.2 == 0.3);
and you will get output as false
.

Utkarsh Sahu
- 409
- 3
- 16
-
1Let me get this straight: since comparing `double`s is not precise we should convert them to `float`s so we lower the precision even further? – Federico klez Culloca Oct 13 '21 at 10:48
-
@FedericoklezCulloca So that's what you want right. You don't want unnecessary precision. Try the example stated by me above and you'll get to know what am I talking about. Also watch : https://stackoverflow.com/questions/588004/is-floating-point-math-broken – Utkarsh Sahu Oct 14 '21 at 10:24