1. 使用内置的`round()`函数:
```python
number = 1.2345
rounded_number = round(number, 2) 将number舍入到两个小数位
print(rounded_number) 输出:1.23
2. 使用格式化字符串(f-string):
```python
a = 1.2345
formatted_a = f'%.2f' % a 保留两位小数
print(formatted_a) 输出:1.23
3. 使用`format()`函数:
```python
a = 1.2345
formatted_a = format(a, '.2f') 保留两位小数
print(formatted_a) 输出:1.23
以上方法都可以用来设置小数位数。`round()`函数是最常用的,而格式化字符串和`format()`函数提供了更多的格式化选项。