在 Python 中,保留小数可通过字符串格式化(使用 "format()" 函数)和数学库函数("round()" 和 "round(<precision>)") 实现,其中 "format()" 用于保留指定位数的小数,而 "round()" 和 "round(<precision>)" 用于四舍五入到最接近的整数或指定精度。

如何使用 Python 保留小数
在 Python 中,保留小数有两种主要方法:字符串格式化和数学库函数。
1. 字符串格式化
字符串格式化通过使用 "format()" 函数保留指定位数的小数。语法如下:
立即学习“Python免费学习笔记(深入)”;
<code class="python">'{value:.<width>f}'.format(value)</code>其中:
-
value是要格式化的数字。 -
<width>指定保留的小数位数。 -
f表示浮点数。
例如:
<code class="python">>>> '{:.2f}'.format(12.3456)
'12.35'</code>2. 数学库函数
Python 提供了两个数学库函数来保留小数:
round()
round() 函数将数字四舍五入到最接近的整数或指定的小数位数。语法如下:
<code class="python">round(number, ndigits=None)</code>
其中:
-
number是要四舍五入的数字。 -
ndigits是要保留的小数位数(可选)。
例如:
<code class="python">>>> round(12.3456, 2) 12.35</code>
round(<precision>)
round(<precision>) 函数将数字四舍五入到指定的精度(小数位数)。语法如下:
<code class="python">round(<number>, <precision>)</code>
例如:
<code class="python">>>> round(12.3456, <precision>=2) 12.35</code>











