-8

How would i turn "0.00" into an int without getting invalid literal for int() with base 10: '0.00' error?

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!

Charles Duffy
  • 280,126
  • 43
  • 390
  • 441

1 Answers1

6

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. Instead, use Decimal:

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

...emits exactly 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
Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
  • For good form, perhaps suggest using str format instead of old formatting, something like `print('{:.2f}'.format(a))` or f-strings like `print(f"{a:.2f}")` for python 3.6+ – Paritosh Singh Mar 24 '19 at 20:04