除法工作并返回足够精度的结果。
所以你的问题只是关于可视化或者确切地说:
设置小数格式
您可以使用字符串格式化为了那个原因。
例如,在 Python 3 中,使用F 弦:
twoFractionDigits = f"{result:.2f}"
or print(f"{result:.2f}")
技巧确实如此.2f
, 一个字符串格式化文字 or 格式说明符表示一个浮点数(f
) 小数点后有两位小数位 (.2
).
也可以看看:
- 使用 f 字符串固定小数点后的数字 https://stackoverflow.com/questions/45310254/fixed-digits-after-decimal-with-f-strings
- 如何在Python中将浮点数格式化为固定宽度 https://stackoverflow.com/questions/8885663/how-to-format-a-floating-number-to-fixed-width-in-python/8885688#8885688
尝试使用 Python-shell:
Python 3.6.9 (default, Dec 8 2021, 21:08:43)
[GCC 8.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import math
>>> a=1.175 #value of a after some division
>>> result = math.floor(a*100)/100
>>> result
1.17
>>> print(result)
1.17
>>> a=25/5 #Now a is perfectly divisible
>>> result = math.floor(a*100)/100
>>> result
5.0
>>> print(result)
5.0
>>> print(f"{result:.2f}")
5.00
将小数格式化为百分比
类似地,您可以将比率表示为百分比:print(f"{result:.2f} %")
prints:
5.00 %
格式化百分比的快捷方式可:print(f"{25/100:.2%}")
将结果转换为25/100 == 0.25
to:
25.00%
注意:格式文字.2%
自动将比率转换为小数点后 2 位数字的百分比,并添加百分号。
使用特定的格式设置小数scale(四舍五入还是截断?)
现在的部分没有四舍五入,只是截断。
作为例子,我们可以使用重复小数 https://en.wikipedia.org/wiki/Repeating_decimal, e.g. 1/6
这需要是rounded or 被截断的(截止)固定数量的小数位后 -scale(相比之下精确).
>>> print(f"{1/6:.2}")
0.17
>>> print(f"{1/6:.2%}")
16.67%
请注意格式化字符串如何不被截断(以0.16
)但四舍五入(到0.17
)。这里的scale在 formatting-literal 中指定为2
(在点之后)。
也可以看看:
- Python中截断至小数点后三位 https://stackoverflow.com/questions/8595973/truncate-to-three-decimals-in-python
- 如何解释数据库中数字的精度和小数位数? https://stackoverflow.com/questions/2377174/how-do-i-interpret-precision-and-scale-of-a-number-in-a-database
- 精度和规模有什么区别? https://stackoverflow.com/questions/5689369/what-is-the-difference-between-precision-and-scale
以固定宽度格式化许多小数(前导空格)
另一个例子是打印多个小数,就像在右对齐的列中一样,这样您就可以轻松地比较它们。
然后使用字符串格式化文字6.2f
添加前导空格(此处固定宽度为 6):
>>> print(f"{result:6.2f}")
5.00
>>> print(f"{100/25*100:6.2f}")
400.00
>>> print(f"{25/100*100:6.2f}")
25.00
See also
此处演示的所有格式化文字也可以使用
- 老式%-格式(也称为“模字符串格式化”)继承自printf method https://en.wikipedia.org/wiki/Printf_format_stringC语言的。好处:这种方式也兼容Python 3.6之前的版本)。
- 新风格
.format
字符串方法(Python 3 引入)
See 瑟克的回答 https://stackoverflow.com/a/70882763/5730279它展示了这些替代方案。
了解有关 Python 中字符串格式的更多信息:
- 真正的Python:Python 3 的 f-Strings:改进的字符串格式化语法(指南) https://realpython.com/python-f-strings/
- 真正的Python:Python 字符串格式化最佳实践 https://realpython.com/python-string-formatting/