This is the mail archive of the cygwin mailing list for the Cygwin project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Re: Bug in printf ?


haro@kgt.co.jp wrote:

> ::How come "0.125" gets printed as "0.12", and not "1.3"?
>                                                     ^^^ "0.13", off cource ;-)

Dealing with integers illustrates the matter more clearly. When
the decimal value is exactly 0.5, then printf should round to the
nearest *even* integer, as far as I know, so you should get

   0   -> 0
   0.5 -> 0
   1   -> 1
   1.5 -> 2
   2   -> 2
   2.5 -> 2
   3   -> 3
   3.5 -> 4
   4   -> 4
   4.5 -> 4
   5   -> 5

Now I realize that Cygwin's printf doesn't get it right, because

   seq 0 .5 5 | while read x; do printf '%-3s -> %.0f\n' $x $x; done

gives

   0   -> 0
   0.5 -> 1
   1   -> 1
   1.5 -> 1
   2   -> 2
   2.5 -> 2
   3   -> 3
   3.5 -> 3
   4   -> 4
   4.5 -> 4
   5   -> 5

Both Solaris' /bin/printf and Perl's printf() give the right
output.

In your examples there is also an additional issue, which is how
numerical values are represented.  Here is Perl:

   seq .105 .01 .155 | while read x; do printf '%-5s -> %.2f\n' $x $x; done

   0.105 -> 0.10
   0.115 -> 0.12
   0.125 -> 0.12
   0.135 -> 0.14
   0.145 -> 0.14
   0.155 -> 0.15

They all seem correct expect the last one.  The reason why 0.155
becomes 0.15 and not 0.16 is that 0.115 can not be represented
exactly.  It is represented as a number which is slightly
*smaller* than 0.155, so it becomes 0.15 after rounding.

Peter

--
Unsubscribe info:      http://cygwin.com/ml/#unsubscribe-simple
Problem reports:       http://cygwin.com/problems.html
Documentation:         http://cygwin.com/docs.html
FAQ:                   http://cygwin.com/faq/

Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]