简体   繁体   English

如何在保留有效位数的同时将 '0.00' 读作 Python 中的数字?

[英]How can I read '0.00' as a number in Python while preserving number of significant digits?

How would i turn "0.00" into an int without getting invalid literal for int() with base 10: '0.00' error?我如何将 "0.00" 转换为 int 而不会得到invalid literal for int() with base 10: '0.00'错误?

Heres my current code;这是我当前的代码;

a = int('0.00')        # which gives me an error
a = int(float('0.00')) # gives me 0, not the correct value of 0.00

any suggestion would be appreciated!任何建议将不胜感激!

If you need to track the number of significant digits past the decimal, neither float nor int is the correct way to store your number.如果您需要跟踪小数点后的有效位数,则floatint都不是存储数字的正确方法。 Instead, use Decimal :相反,使用Decimal

from decimal import Decimal
a = Decimal('0.00')
print(str(a))

...emits exactly 0.00 . ...正好发出0.00

If doing this, you should probably also read the question Significant figures in the decimal module , and honor the accepted answer's advice.如果这样做,您可能还应该阅读小数模块中的重要数字问题,并尊重已接受答案的建议。


Of course, you can also round to a float or an int, and then reformat to the desired number of places:当然,您也可以四舍五入为浮点数或整数,然后重新格式化为所需的位数:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM