在Python中,要保留小数点后几位,可以使用 `round()` 函数。`round()` 函数的基本语法是 `round(number, ndigits)`,其中 `number` 是要四舍五入的数字,`ndigits` 是要保留的小数位数。
下面是一些示例代码:
使用 round() 函数保留小数点后两位
a = 3.
b = round(a, 2)
print(b) 输出:3.14
使用 round() 函数保留小数点后三位
a = 3.
b = round(a, 3)
print(b) 输出:3.142
请注意,`round()` 函数在Python 2和Python 3中的行为略有不同。在Python 2中,`round(2.5)` 的结果是 `2`,而在Python 3中,结果是 `3`。这是因为Python 2中的 `round()` 函数使用的是“银行家舍入法”,而Python 3使用的是“标准舍入法”。
另外,你还可以使用字符串格式化方法,例如使用 `%f` 格式说明符或者 `format()` 函数来控制数字的输出格式。
使用字符串格式化保留小数点后两位
a = 3.
b = "%.2f" % a
print(b) 输出:3.14
使用 format() 函数保留小数点后两位
a = 3.
b = "{:.2f}".format(a)
print(b) 输出:3.14
以上方法都可以用来控制数字的小数点后的位数