possible to round number and convert to string?
r
rt8396 at gmail.com
Sat Aug 1 03:53:51 EDT 2009
On Jul 31, 7:42 pm, "Dr. Phillip M. Feldman" <pfeld... at verizon.net>
wrote:
> This was very close to what I wanted. Thanks! My final code looks like
> this:
>
> def num2str(x,f=4):
> """Convert x (int or float) to a string with f digits to right of
> the decimal point. f may be zero or negative, in which case the decimal
> point is suppressed."""
> s= str(round(x,f))
> if f<=0:
> # Delete decimal point:
> i= s.find('.')
> if i>0: s= s[:i]
> return s
Is it *really* necessary to create a named function for something as
trivial as this?
>>> import math
>>> '%0.3f' %math.pi
'3.142'
>>> '%d' %math.pi
'3'
Seems string formatting is more "pythonic" -- opps, now why did i have
to go and say that... :)
More information about the Python-list
mailing list