possible to round number and convert to string?

John Yeung gallium.arsenide at gmail.com
Fri Jul 31 18:46:22 EDT 2009


On Jul 31, 6:17 pm, "Dr. Phillip M. Feldman" <pfeld... 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 appreciated.

This is what I get in Python 2.6.1 on Windows:

>>> from math import pi
>>> pi
3.1415926535897931
>>> round(pi, 3)
3.1419999999999999
>>> str(round(pi, 3))
'3.142'

John



More information about the Python-list mailing list