如何将"0.00"变成整数而不会出错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