Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Problem with using float or doule in math operation

Status
Not open for further replies.

bthale

Programmer
Oct 31, 2001
108
US
I have to make elemtary calculations on a double, but it is not working. I have 4 variables of type double. I need a 'balance' by taking the first and subtracting the other three. I display Owed, Overpaid, or Balanced depending on the out come. Variable 'balance' shows in Eclipse debugger as 0.0. Here is what is displaying
2648.28
2678.4
0.0
-30.12
1.2779236E-4 (balance should be 0.0)

The balance above seems to be random also.

What gives????
 
There is always a problem with floating point arithmetic in that what might be analytically 0 is numerically a small non-0 number. What I have always done is to have a threshold that is context-specific below which a number is taken to be (manually) 0.

_________________
Bob Rashkin
 
I fixed it, but in my opinion, not a great way. I had to do the math in a database function so that I would get the proper results. I can't believe that after all these years, java (or for that matter any language that has this problem) has not come up with a way to fix this. I bet this one has frustrated many programmers. When I run it through JSTL formatting functions, it displays properly as 0.0, but if you have to use it in logic (>, <=, etc) forget it.
 
It has frustrated programmers but it really isn't Java's fault (or any language's for that matter). The problem is fundamental to the mathematics of finite difference equations rather than the abstract numbers of "organic" (as opposed to machine) mathematics.

_________________
Bob Rashkin
 
You have to use BigDecimal for precise calculations beyond zero.

For addition and substraction, you will do well if don't calculate with doubles of Euros, but with int or long of cents, and just display them as Euros.

But it will not work if you start division (1€/3 => 100¢/3 => 33¢. 3*33¢ == 99¢).

BigDecimal is the common way for dealing with money.

don't visit my homepage:
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top