文章詳情頁(yè)
python - 數(shù)字保留小數(shù)點(diǎn)后幾位的問(wèn)題
瀏覽:116日期:2022-07-15 10:25:49
問(wèn)題描述
我將[-0.32695389161796801, -0.31471406408825409, -0.31475407980700348]中的每個(gè)元素進(jìn)行先保留小數(shù)點(diǎn)后3位再保留小數(shù)點(diǎn)后2位的操作,用如round(round(-0.32695389161796801,3),2)的方式,得到[-0.33000000000000002, -0.32000000000000001, -0.32000000000000001],但我想得到的是[-0.33, -0.32, -0.32],謝謝
問(wèn)題解答
回答1:在使用Python處理精度很重要的浮點(diǎn)數(shù)時(shí),建議使用內(nèi)置的Decimal庫(kù):
from decimal import Decimala = Decimal(’1.0231212121’)a = round(a,3) # Decimal(’1.023’)
如果只是要求看起來(lái)“精確”,那么也可以用字符串的format方法
’{:.2f}’.format(1.0231212121) # ’1.02’
相關(guān)文章:
1. flask - python web中如何共享登錄狀態(tài)?2. python - TypeError: tryMsgcode() takes exactly 2 arguments (0 given)3. mysql 把其中兩行合并怎么解決4. python - django models 為生成的html元素添加樣式。5. 為什么我寫(xiě)的PHP不行6. 為什么我輸入了refresh不會(huì)跳轉(zhuǎn)?請(qǐng)教大神支招!7. phpStudy2017輕巧版mysql無(wú)法啟動(dòng)8. Mysql如何按照日期對(duì)比數(shù)據(jù),求SQL語(yǔ)句9. list - python 求助10. python3.x - python3.5使用pyinstaller打包報(bào)錯(cuò)找不到libpython3.5mu.so.1.0等文件求解?
排行榜

熱門(mén)標(biāo)簽