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 Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Comparing double type numbers

Status
Not open for further replies.

Roncayenne

Programmer
Sep 15, 2003
43
US
Hopefully this is easy and it's my knowledge that is hard!!

I am comparing two double numbers:
if ( h_chrg_amt) == (h_amt_to_pay)
But I am pretty sure the decimal point is the killer..
Some of the numbers are equal up to the 2 decimal position but not after that so it says they are not equal.
If there any way prior to the IF stmt to size the numbers down to only 2 decimal positions for the comparison.

Thanks for the help in advance!
Ron


 
I can think on two ways:

- Multiply by 100 and truncate.
- Transform to string and compare the part you want.

Cheers,
Dian
 
Thanks Dian!

I converted it to a string and that worked fine!
Thanks for the info!

Ron
 
if dealing with money amounts, probably the best way is just to store them as long, and do integer arithmetic. And just print them appropriately. There are BCD libraries that also take care of this. Doubles and floats are a mess to deal with, especially if having to deal with different systems and compilers. They will almost always give you incomplete results.
 
(1) Visual C++ includes a decimal type that is designed for money-type applications. It's probably a lot more efficient than conversion to string.

(2) truncating isn't the same as rounding. If you want to see if the numbers are withing a certain error of each other, look to see if the absolute difference between them is less than a certain decimal amount.

(3) in general, never do a test based on two floating point values being equal; since many decimal numbers can't be represented exactly in binary, the two floating point values you're comparing may never become equal even if, logically, they should be. If you must test whether two floating points are equal, the best thing to do is the test as in (2) above, checking against what you believe to be your machine precision. i.e. define some constant with the smallest value that is of any interest to you and check if the two target numbers differ by <= the tinyNumber constant.
 
... sorry about suggestion No. 1; I forgot what thread I was in.
 
Compare doubles on equality as usual (and classic) for floating point numbers:
Code:
#define EPS (0.01) /* usually 1e-6 */
...
if (fabs(x-y) < EPS) ...
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top