Thread: Weird problem with 36 and 39?

1. Member
Join Date
Jan 2011
Location
Park Ridge, IL
Posts
10
Rep Power
0

Weird problem with 36 and 39?

I am writing a small program for a school assignment that requests user input for the number of checks written per month. The program then multiplies that number by a per-check rate, which varies depending on the number of checks written, and adds in \$10. While testing the program, I discovered that it works perfectly - unless I enter 36 or 39, or 48 or 52, which is when the math gets screwy. For example -

If I enter 34, I get 12.72; if I enter 35, I get 12.8 (another .08); but when I enter 36, I get 12.8799999; 37 gets me 12.96; 38 gets me 13.04; but then 39 gets me 13.1200001!

The .000001 that is missing from the answer for 36 comes out added to the answer for 39? This same anomaly occurs with 48 and 52.

Any ideas?

2. Welcome to the world of floating point arithmetic on a digital computer. There's nothing strange going on, but you're learning that exact solutions often don't exist and that we generally accept a close approximation. Please read this link for more information on this: floating point

A solution is to format the number when you wish to display it using either a DecimalFormat object some variant of a Formatter object (such as System.out.printf("...") or String.format(...)).

3. Moderator
Join Date
Feb 2009
Location
New Zealand
Posts
4,565
Rep Power
12
Please bear in mind that what you are reading are Strings not numeric quantities. And that computers have limited precision.

If you want output that looks like reasonable money amounts try:

Java Code:
`System.out.printf("\$%.2f", value);`

where value is the numeric quantity you have calculated and want to display properly. The syntax for the format string ("%.2f") is explained in the Formatter API documentation.

Alternatively look into the DecimalFormat class.

The two approaches have different strengths and weaknesses - but for simple problems both will do and both are worth knowing about.

----------------------------------

In case someone suggests it, do not round your numeric quantities as this cannot make them more accurate. The computers precision may be limited but you can trust that its accuracy is as good as it gets.
Last edited by pbrockway2; 02-06-2011 at 05:00 AM.

4. Member
Join Date
Jan 2011
Location
Park Ridge, IL
Posts
10
Rep Power
0
Once again, Java Forums has solved my problem. Thanks to both of you for your help.

john