目錄
- 前言
- 1. 字符串格式
- 2. round函數
- 3. Decimal模塊
- 4. numpy庫
- 5. Demo
前言
在Python中,保留小數點后特定位數可以通過多種方式實現
以下是幾種常見的方法,并附上相應的代碼示例:
- 使用字符串格式化(String Formatting)
- 使用round()函數
- 使用Decimal模塊
- 使用numpy庫
1. 字符串格式
方法1:使用f-strings (Python 3.6及以上)
value = 3.141592653589793
formatted_value = f"{value:.2f}"
print(formatted_value) # 輸出: 3.14
方法2:使用str.format()
value = 3.141592653589793
formatted_value = "{:.2f}".format(value)
print(formatted_value) # 輸出: 3.14
方法3:使用百分號 (%) 格式化
value = 3.141592653589793
formatted_value = "%.2f" % value
print(formatted_value) # 輸出: 3.14
2. round函數
value = 3.141592653589793
rounded_value = round(value, 2)
print(rounded_value) # 輸出: 3.14
3. Decimal模塊
Decimal模塊提供更高的精度和控制,可以精確控制小數點后的位數
from decimal import Decimal, ROUND_HALF_UPvalue = Decimal('3.141592653589793')
rounded_value = value.quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)
print(rounded_value) # 輸出: 3.14
4. numpy庫
大量的數值計算,使用numpy庫是個好選擇
import numpy as npvalue = 3.141592653589793
rounded_value = np.round(value, 2)
print(rounded_value) # 輸出: 3.14
5. Demo
總體Demo如下:
import numpy as np
from decimal import Decimal, ROUND_HALF_UPvalue = 3.141592653589793# 使用f-strings
formatted_value_f = f"{value:.2f}"
print(f"f-strings: {formatted_value_f}")# 使用str.format()
formatted_value_format = "{:.2f}".format(value)
print(f"str.format(): {formatted_value_format}")# 使用百分號 (%) 格式化
formatted_value_percent = "%.2f" % value
print(f"百分號格式化: {formatted_value_percent}")# 使用round()函數
rounded_value_round = round(value, 2)
print(f"round(): {rounded_value_round}")# 使用Decimal模塊
decimal_value = Decimal('3.141592653589793')
rounded_value_decimal = decimal_value.quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)
print(f"Decimal模塊: {rounded_value_decimal}")# 使用numpy庫
rounded_value_numpy = np.round(value, 2)
print(f"numpy庫: {rounded_value_numpy}")
截圖如下: