python保留小數(shù)點位數(shù)的多種方式(附demo)
前言
在Python中,保留小數(shù)點后特定位數(shù)可以通過多種方式實現(xiàn)
以下是幾種常見的方法,并附上相應的代碼示例:
- 使用字符串格式化(String Formatting)
- 使用round()函數(shù)
- 使用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函數(shù)
value = 3.141592653589793 rounded_value = round(value, 2) print(rounded_value) # 輸出: 3.14
3. Decimal模塊
Decimal模塊提供更高的精度和控制,可以精確控制小數(shù)點后的位數(shù)
from decimal import Decimal, ROUND_HALF_UP value = Decimal('3.141592653589793') rounded_value = value.quantize(Decimal('0.01'), rounding=ROUND_HALF_UP) print(rounded_value) # 輸出: 3.14
4. numpy庫
大量的數(shù)值計算,使用numpy庫是個好選擇
import numpy as np value = 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_UP value = 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()函數(shù) 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}")
截圖如下:
到此這篇關于python保留小數(shù)點位數(shù)的多種方式(附demo)的文章就介紹到這了,更多相關python保留小數(shù)點位數(shù)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
- python 正確保留多位小數(shù)的實例
- python 除法保留兩位小數(shù)點的方法
- python格式化輸出保留2位小數(shù)的實現(xiàn)方法
- python保留小數(shù)位的三種實現(xiàn)方法
- python中round函數(shù)保留兩位小數(shù)的方法
- Python如何保留float類型小數(shù)點后3位
- python保留兩位小數(shù)的3種方法實例
- python保留小數(shù)函數(shù)的幾種使用總結
- python保留若干位小數(shù)?format與round的使用區(qū)別
- Python保留指定位數(shù)小數(shù)的5種方法總結
- 如何利用Python保留指定位數(shù)的小數(shù)
- Python除法保留兩位小數(shù)點的三種方法實現(xiàn)
- python保留兩位小數(shù)的五種方法
- python實現(xiàn)保留小數(shù)位數(shù)的3種方法
相關文章
python數(shù)據(jù)可視化Seaborn畫熱力圖
這篇文章主要介紹了數(shù)據(jù)可視化Seaborn畫熱力圖,熱力圖的想法其實很簡單,用顏色替換數(shù)字,下面我們來看看文章對操作過程的具體介紹吧,需要的小伙伴可以參考一下具體內(nèi)容,希望對你有所幫助2022-01-01Python+PyQt5實現(xiàn)網(wǎng)口功能測試詳解
這篇文章主要為大家詳細介紹了Python+PyQt5實現(xiàn)網(wǎng)口功能測試的相關知識,文中的示例代碼講解詳細,感興趣的小伙伴可以跟隨小編一起學習一下2024-02-02python操作MySQL數(shù)據(jù)庫的方法分享
堅持每天學一點,每天積累一點點,作為自己每天的業(yè)余收獲,這個文章是我在吃飯的期間寫的,利用自己零散的時間學了一下python操作MYSQL,所以整理一下2012-05-05