在Python中,要保留浮点数的两位小数,你可以使用以下几种方法:
1. 使用 `round()` 函数:
number = 3.14159rounded_number = round(number, 2)print(rounded_number) 输出:3.14
2. 使用字符串格式化(`format()` 函数):
number = 3.14159formatted_number = "{:.2f}".format(number)print(formatted_number) 输出:3.14
3. 使用 `decimal` 模块:

from decimal import Decimalnumber = Decimal('3.')rounded_number = round(number, 2)print(rounded_number) 输出:3.14
4. 使用 `f-string`(Python 3.6及以上版本):
value = 3.formatted_number_f = f"{value:.2f}"print(formatted_number_f) 输出:3.14
5. 使用 `numpy` 库(如果需要处理大量数据):
import numpy as npvalue = np.array([3.])formatted_number_np = np.format_float_scientific(value, precision=2)print(formatted_number_np) 输出:3.14
