possible to round number and convert to string?

Mark Dickinson dickinsm at gmail.com
Sat Aug 1 04:36:11 EDT 2009


On Jul 31, 11: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').

Python's string formatting does exactly this.

Python 2.6.2 (r262:71600, Jul  8 2009, 09:56:31)
[GCC 4.0.1 (Apple Inc. build 5490)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> num2str = '{0:.{1}f}'.format
>>> num2str(3.14159, 3)
'3.142'

(In Python 3.1, num2str = '{:.{}f}'.format  is enough.)


Mark



More information about the Python-list mailing list