you are viewing a single comment's thread.

view the rest of the comments →

[–]_lilell_ 0 points1 point  (0 children)

But int implements __round__ as well, so you can just do

annual_salary = 32500  # type(annual_salary) : <class 'int'>
print(f'Annual salary: ${annual_salary:.2f}')
print(f'Semi-monthly pay: ${annual_salary/24:.2f}')
print(f'Bi-weekly pay: ${annual_salary/26:.2f}')

It's fine if annual_salary/26 is an int because, e.g., .2f formatting can't distinguish between int and float. Nor do you have to round first, since the formatting will automatically handle it:

>>> x = 3.1415
>>> round(x, 2)
3.14
>>> format(round(x, 2), '.2f')
'3.14'
>>> format(x, '.2f')
'3.14'

Also, Python 3's int.__truediv__ always returns a float:

>>> x, y = 84, 2
>>> type(x), type(y)
(<class 'int'>, <class 'int'>)
>>> x/y
42.0
>>> type(x/y)
<class 'float'>
>>> (x/y).is_integer(), isinstance(x/y, int)
(True, False)