简体   繁体   English

将变量的输出显示为超过2个小数位

[英]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. 我试图将我的加法输出显示超过2位小数。

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? 如果这是一个函数,我怎么能返回完整的数字?

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. 当将float转换为字符串(打印自动执行此操作)时,python将其限制为仅有12个最高位数加上小数点。

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: 默认为6位数,但您可以指定更高的精度:

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

Alternatively, python offers a newer string formatting method too: 或者,python也提供了一种更新的字符串格式化方法

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

You already have the full number. 你已经有了完整的号码。 Use a custom format specifier on output. 在输出中使用自定义格式说明符。

>>> print '%.15f' % range_key
1347053222.790798902511597

You'll find that if you hard-code the number of digits to print, you'll sometimes get too few or worse yet go past the floating-point precision and get meaningless digits at the end. 你会发现,如果你硬编码要打印的数字位数,你有时会得到太少或更糟,但仍然超过浮点精度并在最后得到无意义的数字。 The standard floating point number only has precision to about 15 digits. 标准浮点数的精度仅为15位左右。 You can find out how many of those digits are to the right of the decimal point with this simple formula: 您可以使用以下简单公式找出小数点右侧有多少这些数字:

digits_right = 14 - int(math.log10(value))

Using that you can create an appropriate %f format: 使用它您可以创建适当的%f格式:

fmt = '%%0.%df' % max(0, digits_right)
>>> f = 1/7.
>>> repr(f)
'0.14285714285714285'
>>> str(f)
'0.142857142857'
>>> f
0.14285714285714285
>>> print f
0.142857142857
>>> '%.15f' % f
'0.142857142857143'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM