Python 中在小数点后向浮点数添加零
使用 format() 函数将零添加到小数点后的浮点数,例如 result = format(my_float, ‘.3f’)。 该函数会将数字格式化为小数点后恰好 N 位数字。
my_float = 3.0
result = format(my_float, '.3f')
print(result) # ?️ '3.000'
print(type(result)) # ?️ <class 'str'>
我们使用格式函数将零添加到小数点后的浮点数。
格式说明符中的 f 类型代表定点表示法。
my_float = 3.0
result_1 = format(my_float, '.3f')
print(result_1) # '3.000'
result_2 = format(my_float, '.4f')
print(result_2) # '3.0000'
result_3 = format(my_float, '.6f')
print(result_3) # '3.000000'
这是必要的,因为 Python 不会保留任何不重要的尾随零。
my_float = 3.00000000
print(my_float) # ?️ 3.0
另一种方法是使用格式化的字符串文字。
my_float = 3.0
result = f'{my_float:.3f}'
print(result) # ?️ '3.000'
格式化字符串文字 f-strings 让我们通过在字符串前加上 f 来在字符串中包含表达式。
my_str = 'is subscribed:'
my_bool = True
result = f'{my_str} {my_bool}'
print(result) # ?️ is subscribed: True
确保将表达式用大括号括起来 – {expression}。
我们还能够在 f 字符串的表达式中使用格式规范迷你语言。
my_float = 3.2
result_1 = f'{my_float:.3f}'
print(result_1) # ?️ '3.200'
result_2 = f'{my_float:.5f}'
print(result_2) # ?️ '3.20000'
result_3 = f'{my_float:.6f}'
print(result_3) # ?️ '3.200000'
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。