Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
430 views
in Technique[技术] by (71.8m points)

python - Displaying the output of a variable to more than 2 decimal places

I'm trying to display the output of my addition to more than 2 decimal places.

import time
import random

max_number = 1000000.0
random_time = random.randrange(1, max_number-1) / max_number
range_key = int(time.time()) + random_time

range_key
>>> 1347053222.790799

print range_key
>>> 1347053222.79

How can I print the full number? If this were a function, how could I return the full number?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

When turning a float into a string (printing does this automatically), python limits it to only the 12 most significant digits, plus the decimal point.

When returning the number from a function, you always get the full precision.

To print more digits (if available), use string formatting:

print '%f' % range_key  # prints 1347053958.526874

That defaults to 6 digits, but you can specify more precision:

print '%.10f' % range_key  # prints 1347053958.5268740654

Alternatively, python offers a newer string formatting method too:

print '{0:.10f}'.format(range_key)  # prints 1347053958.5268740654

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...