如何扩展长数字(以 e+## 结尾)以扩展形式显示? [英] How do I expand a long number (ending in e+##) to show in expanded form?
问题描述
所以,这可能是一个简单的问题,但我在任何地方都找不到答案.
例如我有一个简单的程序,我想像这样将 a 除以 b:
def main():a = 12345678900000000b = 1.25答案 = (a/b)打印(答案)主要的()
这个特定的例子将导致 9.87654312e+15.如何让 Python 忽略简化我的数字而只给我整数?
提前致谢,抱歉,如果它真的很基础,我不会问我是否可以通过 Google 找到它.
您看到浮点数的默认 str()
转换在起作用.您可以通过明确格式化数字来选择不同的转换.
format()
函数可以为您做到这一点:
有关更多选项,请参阅格式规范迷你语言文档.'f'
格式只是以下格式之一:
固定点.将数字显示为定点数.默认精度为 6.
默认精度导致.000000
小数点后六位数字;你可以使用 .
但要考虑到小数会四舍五入以符合要求的精度.
g
格式在使用指数 (e
) 和 f
符号之间切换,取决于数字的大小,但不会如果数字是整数,则包括小数;你可以在 'g'
中使用一个非常大的精度来避免完全打印小数:
明确地说,str(n)
等同于 format(n, '.12g')
, repr(n)
是 format(n, '.17g')
;当指数大于精度时,两者都可以使用指数格式.
So, this may be a simple question but I'm having some trouble finding the answer anywhere.
Take for example I have a simple program where I want to divide a by b like so:
def main():
a = 12345678900000000
b = 1.25
answer = (a / b)
print(answer)
main()
This particular example would result in 9.87654312e+15. How do I get Python to ignore simplifying my number and just give me the whole number?
Thanks in advance, sorry if it's really basic, I wouldn't have asked if I could have found it through Google.
You are seeing the default str()
conversion for floating point numbers at work. You can pick a different conversion by formatting the number explicitly.
The format()
function can do this for you:
>>> n = 9.87654312e+15
>>> format(n, 'f')
'9876543120000000.000000'
See the Format Specification Mini-Language documentation for more options. The 'f'
format is but one of several:
Fixed point. Displays the number as a fixed-point number. The default precision is 6.
The default precision resulting in the .000000
six digits after the decimal point; you can alter this by using .<precision>f
instead:
>>> format(n, '.1f')
'9876543120000000.0'
but take into account that decimals are rounded to fit the requested precision.
The g
format switches between using exponents (e
) and f
notation, depending on the size of the number, but won't include decimals if the number is whole; you could use a very large precision with 'g'
to avoid printing decimals altogether:
>>> format(n, '.53g')
'9876543120000000'
To be explicit, str(n)
is the same as format(n, '.12g')
, repr(n)
is format(n, '.17g')
; both can use the exponent format when the exponent is larger than the precision.
这篇关于如何扩展长数字(以 e+## 结尾)以扩展形式显示?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!