Is it a bug or expected behavior to have rounding behave differently depending on the number of visible decimal places?
Demo via Interactive Interpreter
Python 3.8.10
>>> a = 1.555
>>> f'{a:.0f}'
'2'
>>> f'{a:.1f}'
'1.6'
>>> f'{a:.2f}'
'1.55'
>>> f'{a:.3f}'
'1.555'
One way to make it accurate is to use
Decimal:But, you could see
Decimal(1.555)will output next:Above could explain why we get the
1.55, as the 3rd number is 4.To fix that, we should change
floattostrasfloatis not accurate.So, when you need accurate, consider to using
Decimal.