From: buers AT gmx DOT de (Dieter Buerssner) Newsgroups: comp.os.msdos.djgpp Subject: Re: Discrepancy in printing a type float Date: 15 May 2000 20:10:04 GMT Lines: 35 Message-ID: <8fpsts.3vs4rf7.0@buerssner-17104.user.cis.dfn.de> References: <39204d14 DOT 77225094 AT news-server DOT socal DOT rr DOT com> NNTP-Posting-Host: pec-142-59.tnt9.s2.uunet.de (149.225.142.59) Mime-Version: 1.0 Content-Type: text/plain; charset=ISO-8859-1 Content-Transfer-Encoding: 8bit X-Trace: fu-berlin.de 958421404 99954 149.225.142.59 (16 [17104]) X-Posting-Agent: Hamster/1.3.13.0 User-Agent: Xnews/03.02.04 To: djgpp AT delorie DOT com DJ-Gateway: from newsgroup comp.os.msdos.djgpp Reply-To: djgpp AT delorie DOT com Andy17 wrote: >I'm using DJGPP/RHIDE and am producing what appears to me a strange >result when printing a float variable. After assigning a value and >calling printf to display the result: > >profit = 2150.48; >printf("Profit $%f\n", profit); > >it produces: > >Profit: $2150.479980 The problem is, that floating point values in DJGPP (and almost all modern computers, pocket calculators are an exception) have a base of two, and your "input" has a base of ten. In general, you cannot represent a decimal value with a finite number of digits as an exact floting point number. The problem is much like representing 1/3 in base ten, where you need a infinite number of digits, 0.33333333333... In base three, this would just be 0.1 (as 1/10 is 0.1 in base ten). So if you have a finite number of digits, you have to round the result. For 6 decimal digits, 1/3 may be 0.333333 and 2/3 0.666667. It turns out, that the closest number to your input, that is an exact floating point value of type float is 2150.479980468750000... The output you got, is this number, correctly rounded to 6 places after the decimal point. That much said, if you use type double, your number will be printed, as you expect. But the problem is still there, and it will show when you print more digits. As a general rule, you can expect about 7-8 correct significant decimal digits for type float and about 16 significant digits for type double. -- Regards, Dieter Buerssner