Floating numbers and str

Dan Bishop danb_83 at yahoo.com
Wed Nov 9 19:20:08 EST 2005


Grant Edwards wrote:
> On 2005-11-09, Tuvas <tuvas21 at gmail.com> wrote:
>
> > I would like to limit a floating variable to 4 signifigant digits, when
> > running thorugh a str command.
>
> Sorry, that's not possible.

Technically, it is.

>>> class Float4(float):
...    def __str__(self):
...       return '%.4g' % self
...
>>> x = Float4(1.23456789)
>>> str(x)
'1.235'

But, of course, I'd recommend just using '%.4g'%x directly.




More information about the Python-list mailing list