How can I get a precise 0.0 when using double/float? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson

How can I get a precise 0.0 when using double/float?

I'm using double attributes for a method that determines the (zero points? (I'm German sorry) ) of a square function. How can I use an if function to ask when the value is exactly 0? I'm out of ideas because it never gets exactly 0.0 when calculating with float or double does it? Greetings

18th Nov 2016, 1:21 PM
Mitial W
Mitial W - avatar
2 Answers
+ 2
usually its often not getting exactly 0.0 i see two possible solutions to the problem. 1. use something like if(Math.abs(a-b) < 0.0000001) { // a and b are equal } else { // a and b are not equal } 2. round your double values with something like that: double d1 = 1.0012345; BigDecimal bd = new BigDecimal(d1); bd = bd.setScale(4, RoundingMode.HALF_UP); System.out.println(bd.doubleValue());
18th Nov 2016, 2:55 PM
- 1
What i the difference between using if statements and case ???
22nd Nov 2016, 12:17 AM
Afif Asri
Afif Asri - avatar