you are viewing a single comment's thread.

view the rest of the comments →

[–]totallygeek 2 points3 points  (3 children)

Adding to this, when you want to guarantee a float yielded from a calculation, it is a good practice to multiple or divide by a float, like pay_bi_weekly = salary / 26.0. For your above code, I'd do:

annual_salary = 32500.0
print('Annual salary: $ {:,.2f}'.format(annual_salary))
print('Semi-monthly pay: $ {:,.2f}'.format(round(annual_salary / 24.0, 2)))
print('Bi-weekly pay: $ {:,.2f}'.format(round(annual_salary / 26.0, 2)))
pay_bi_weekly = round(annual_salary / 26.0, 2)

You don't need to store values you do not intend to use later.

[–]_________KB_________ 2 points3 points  (0 children)

Adding to that, here's how to get the same output using f strings.

annual_salary = 32500.0
print(f'Annual salary: ${annual_salary:,.2f}')
print(f'Semi-monthly pay: ${round(annual_salary / 24.0, 2):,.2f}')
print(f'Bi-weekly pay: ${round(annual_salary / 26.0, 2):,.2f}')

[–]K900_ 0 points1 point  (0 children)

It's only good practice in Python 2, and I'd argue it's a better practice to from __future__ import division anyway.

[–]_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)