results of division

Donn Cave donn at u.washington.edu
Thu Dec 9 14:49:36 EST 2004


In article <cp9ska$s1o$1 at solaris.cc.vt.edu>,
 Brad Tilley <bradtilley at gmail.com> wrote:
> > Brad Tilley wrote:
> > 
> >> What is the proper way to limit the results of division to only a few 
> >> spaces after the decimal? I don't need rocket-science like precision. 
> >> Here's an example:
> >>
> >> 1.775 is as exact as I need to be and normally, 1.70 will do
...
> I'm summing up the bytes in use on a hard disk drive and generating a 
> report that's emailed based on the percentage of the drive in use.

Stilling guessing a little about what you're trying to do -
probably implicitly or explicitly invoking the "repr" function
on this values (implicitly for example via repr() or str() on
a sequence of them.)  So,

  a = [1.775, 1.949]
  print a
yields
    [1.7749999999999999, 1.9490000000000001]

You will get something more like what you want with
the str() function instead.  str(1.775) == '1.775'



  from types import FloatType
  class ClassicFloat(FloatType):
      def __repr__(self):
          return self.__str__()

  print map(ClassicFloat, [1.775, 1.949])

yields
    [1.775, 1.949]


(Seems to me the standard float type behaved like
this in Python 1.5.4, hence "classic".)

   Donn Cave, donn at u.washington.edu



More information about the Python-list mailing list