possible to round number and convert to string?

  • Thread starter Dr. Phillip M. Feldman
  • Start date
D

Dr. Phillip M. Feldman

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.
 
J

John Yeung

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:
'3.142'

John
 
M

Mark Dickinson

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.'3.142'

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


Mark
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,201
Messages
2,571,048
Members
47,651
Latest member
VeraPiw932

Latest Threads

Top