[Tutor] Is there anyway to set how many numbers are used after the decimal in floating numbers?
Danny Yoo
dyoo at hkn.eecs.berkeley.edu
Thu Aug 18 22:40:28 CEST 2005
On Thu, 18 Aug 2005, Nathan Pinno wrote:
> Is there anyway to set how many numbers are used after the decimal in
> floating numbers? It would be nice if the answer could be rounded to 2
> decimal spots, instead of the ten millionths spot.
Hi Nathan,
If you want to print a number with two decimal places, you may want to use
a string formatting operator. String Formatting allows us to format
numbers into particular ways. For example:
#######
def to_ten_digits(n):
"""Given a number n, returns a string representation of that
number with ten digits. We pad empty spaces with zero."""
return "%010f" % n
#######
shows that we can turn numbers into ten-digit strings:
#######
>>> to_ten_digits(42)
'042.000000'
#######
This is not what you're asking for, exactly, but take a look at:
http://www.python.org/doc/lib/typesseq-strings.html
http://www.python.org/doc/tut/node9.html#SECTION009100000000000000000
for more information on String Formatting: you can do floating point
formatting with it too.
More information about the Tutor
mailing list