[英]python float a real number preserving significant digits even when are all are zero
[英]How can I read '0.00' as a number in Python while preserving number of significant digits?
我如何將 "0.00" 轉換為 int 而不會得到invalid literal for int() with base 10: '0.00'
錯誤?
這是我當前的代碼;
a = int('0.00') # which gives me an error
a = int(float('0.00')) # gives me 0, not the correct value of 0.00
任何建議將不勝感激!
如果您需要跟蹤小數點后的有效位數,則float
和int
都不是存儲數字的正確方法。 相反,使用Decimal
:
from decimal import Decimal
a = Decimal('0.00')
print(str(a))
...正好發出0.00
。
如果這樣做,您可能還應該閱讀小數模塊中的重要數字問題,並尊重已接受答案的建議。
當然,您也可以四舍五入為浮點數或整數,然后重新格式化為所需的位數:
a = float('0.00')
print('%.2f' % a) # for compatibility with ancient Python
print('{:.2f}'.format(a)) # for compatibility with modern Python
print(f"{a:.2f}") # for compatibility with *very* modern Python
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.