[英]How to convert dataframe to list without adding more decimal places in python
[英]python: convert a list into list with 5 decimal places
如何將列表轉換為5位小數的列表?
list1 = [0.23400000000, 0.3456222222, 0.1278234, 0.78433333]
期望:
list1 = [0.23400, 0.34562, 0.12782, 0.78433]
我不希望0.34562是0.34561,我需要保留原樣的值,但要保留5個小數點。
我不相信您可以獲得0.23400
浮動。 我可以提供的最接近的解決方案是:
list1 = [0.23400000000,0.3456222222,0.1278234,0.78433333]
list1 = [round(i,5) for i in list1]
>>> print(list1)
[0.234, 0.34562, 0.12782, 0.78433]
我不知道為什么您需要0.23400
的浮點數,因為它沒有提供0.234
任何其他數學意義。 除非您真正要查找的是字符串。
您可以使用decimal
模塊:
import decimal
decimal.getcontext.prec() = 5 # Use 5 decimal places
list1 = [0.23400000000,0.3456222222,0.1278234,0.78433333]
list2 = [decimal.Decimal(x) + decimal.Decimal(0) for x in list1] # addition is necessary to trigger rounding
print(list2) # [Decimal('0.23400'), Decimal('0.34562'), Decimal('0.12782'), Decimal('0.78433')]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.