possible to round number and convert to string?
malaclypse2 at gmail.com
Fri Jul 31 18:42:03 EDT 2009
On Fri, Jul 31, 2009 at 6:17 PM, Dr. Phillip M.
Feldman<pfeldman at verizon.net> wrote:
> I'd like to be able to convert a float to a string representation in which
> the number is rounded to a specified number of digits. If num2str is a
> hypothetical function that does this, then num2str(pi,3) would be '3.142'
> (not '3.141'). I've been told that there is no such function in Python. I
> tried to write this myself, but wasn't successful. Any suggestions will be
You should be able to do this with standard string formatting. (
>>> from math import pi
>>> "%0.3f" % pi
If you need it as a function, you could do something like this:
>>> def num2str(num, precision):
return "%0.*f" % (precision, num)
>>> num2str(pi, 4)
Does that do what you need?
More information about the Python-list