CompuServe Thread

#Double != Double

6 messages in this thread
#86610From: Donald WahlSep 27, 1987 9:49 AM
I using Manc C vs 3.4 and trying to compare 2 double values. They start as ascii strings and are converted to doubles with double atof(). The decimal precision is 2 places (dollar values actually). When I compare 2 values that should be equal it doesn't work. Using printf I find garbage in the 11th decimal place. I'm compiling with cc +fi and linking with ln mx.lib c.lib. Any hints?
#86635From: John DraperSep 27, 1987 6:33 PM
Donald, As a general rule, comparing floating point numbers will not work without some extra effort on your part. The exact value in a floating point variable can be off by a few bits, causing the compare to fail. this is due to the inexact representation of a number in binary. You might want to try getting rid of the insignificant decimal places by mutiplying by a power of 10 and comparing the integer part. For example: a = 5.1234789 b = 5.1234788 int(a*100 = 512) int(b*100 = 512) Compare should work. Regards, Larry.
#86799From: Donald WahlSep 28, 1987 7:20 PM
That's rather dissapointing news. I don't really enjoy the thought of finding each floating point compare and rewriting the code. I hoped that something with a name a fancy as IEEE Double Precision could compare 2 dollar values.
#86822From: John DraperSep 28, 1987 8:47 PM
Donald, It's normal practice when using floating point to never compare values. For dollars/cents, you are better off using integers. Regards, Larry.
#86885From: Richard Rae/SYSOPSep 29, 1987 3:48 PM
Lordy, lordy, LORDY, you should reconsider on using FP to represent money!!! Unless a floating point package is constructed using BCD (accurate but slow), it is totally unsuitable for any application which requires 100% accuracy at its granularity level. I would strongly urge you to go with integers. There are two approaches: scale the numbers, or keep a separate set of integers for dollars and cents. I'd suggest scaling as the easier route; simply work in cents, and place the decimal point properly when doing output. Closing note: this is not a failing of C. This applies to effectively all floating point implementations (unless, as mentioned, they are done in BCD), and is one of the more memorable gotchas one learns in CS-101. Rick
#86956From: Donald WahlSep 29, 1987 10:01 PM
So that's what I'm doing wrong, changing from floating pt to int isn't what I wanted to do but it does make sense (almost, I'll take it on faith that FP isn't accurate).