[英]Is 6 the default decimal digits of floating point in python format?
I'm learning the format method in python and tried to convert 1 to a float by it.我正在学习 python 中的格式方法,并尝试将 1 转换为浮点数。
"{:f}".format(1)
But why is the output '1.000000'
instead of '1.0'
?但是为什么 output
'1.000000'
而不是'1.0'
?
I suppose this is the default output if you do not specify the number of decimals.如果您不指定小数位数,我想这是默认的 output。 Using the 3.6+ f-string format:
使用 3.6+ f-string 格式:
f'{1.123456789:f}'
'1.123457'
f'{1:.1f}'
'1.0'
f'{1.12345678901234567:.10f}'
'1.1234567890'
Now a whole other question is what is the precision of a floating point number, for example现在另一个问题是浮点数的精度是多少,例如
f'1.1:.20f'
'1.10000000000000008882'
which seems to suggest a floating point gives up to 16 decimal accuracy.这似乎表明浮点最多可以提供 16 位小数精度。 If you need more then you need to use the
Decimal
module Decimal fixed point and floating point arithmetic如果您需要更多,则需要使用
Decimal
模块Decimal 定点和浮点运算
The Python documentation says for formatting with f
“Displays the number as a fixed-point number. Python 文档说使用
f
格式化“将数字显示为定点数。 The default precision is 6.”默认精度为 6。”
Note that not all Python implementations use the same format for floating-point.请注意,并非所有 Python 实现都使用相同的浮点格式。 As the documentation notes , most modern machines use IEEE-754 floating-point arithmetic, and almost all platforms map Python
float
objects to IEEE-754 basic 64-bit binary format, but this is not guaranteed.如文档所述,大多数现代机器使用 IEEE-754 浮点运算,并且几乎所有平台 map Python 将
float
对象转换为 IEEE-754 基本 64 位二进制格式,但这不能保证。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.