如何在保留有效数字位数的同时在Python中读取“ 0.00”作为数字?

sta*_*own -8 python python-3.x

我如何将“ 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
Run Code Online (Sandbox Code Playgroud)

任何建议,将不胜感激!

Cha*_*ffy 6

如果您需要跟踪小数点后的有效位数,那么存储数字的正确方法float也不int是。而是使用Decimal

from decimal import Decimal
a = Decimal('0.00')
print(str(a))
Run Code Online (Sandbox Code Playgroud)

... 准确地 发出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
Run Code Online (Sandbox Code Playgroud)