programming forums Java Java JSRs Mobile Certification Databases Caching Books Engineering OS Languages Paradigms IDEs Build Tools Frameworks Products This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

# Using double as a percentage

Ranch Hand
Posts: 211
Is using a double as a percentage generally a bad idea?

I'm working on a program that works with probabilities which I am representing with doubles. Given the probability of something happening (P), I need to calculate the probability that event doesn't happen, which is normally just (1 - P). I then use those probabilities for other operations. It was a bit surprising to me that double doesn't work properly for this.

Example:
double d = 0.8;
System.out.println(1-d);

I get 0.19999999999999996 instead of just 0.2, which is weird because if i use 0.4 for d then I do actually get 0.6. I suppose I can just not worry about the difference and just format my outputs, or is there some sort of shortcut to make the values match up right? Should I just throw out using double altogether?

Ranch Hand
Posts: 75
1
I'm not sure why you're receiving your results (I did too...), but if you use the Double wrapper class:

The displayed result is 0.2, this seems rather odd though...

author
Sheriff
Posts: 23295
125

See item 20 of the Java Beginner FAQ for some details...

http://www.coderanch.com/how-to/java/JavaBeginnersFaq

Henry

Tyson Lindner
Ranch Hand
Posts: 211
Henry Wong wrote:
See item 20 of the Java Beginner FAQ for some details...

http://www.coderanch.com/how-to/java/JavaBeginnersFaq

Henry

Mind giving some cliffs?

I tried using BigDecimal but it gives the same problem.

BigDecimal b = new BigDecimal(0.8);
System.out.println((new BigDecimal(1)).subtract(b));

gives me 0.1999999999999999555910790149937383830547332763671875

In a professional program, how would the above operation be handled?

Bartender
Posts: 2087
44
• 1

Tyson Lindner
Ranch Hand
Posts: 211
BigDecimal with the string works. Thanks for the help.

Apparently the problem was that double isn't exact to begin with, not because of the operation.

double d = 0.8
System.out.println(d);

gives 0.8

but
BigDecimal d = new BigDecimal(0.8);
System.out.println(d);

gives 0.8000000000000000444089209850062616169452667236328125

The above is the actual value of the original double, we just don't see it like that because java rounds it off. So sometimes when we subtract double values we still have zeros till the rounding point, and java won't bother printing those, but other times enough is subtracted to dip under that threshold value and java is forced to print all those nines (but still prints a rounded number).

Paweł Baczyński
Bartender
Posts: 2087
44
That's right . Glad we could help .