2

Other questions have indicated that Python f-strings round digits at a certain decimal place, as opposed to truncating them.

I can show this with the following example:

>>> number = 3.1415926
>>> print(f"The number rounded to two decimal places is {number:.2f}")
The number rounded to two decimal places is 3.14
>>>
>>> number2 = 3.14515926
>>> print(f"The number rounded to two decimal places is {number2:.2f}")
The number rounded to two decimal places is 3.15

However, I've encountered another situation where Python seems to truncate the number:

>>> x = 0.25
>>> f'{x:.1f}'
'0.2'

I would have imagined that 0.25, to one decimal place, would round to 0.3. Am I missing something, or is this behavior inconsistent?

martineau
  • 119,623
  • 25
  • 170
  • 301
jxmorris12
  • 1,262
  • 4
  • 15
  • 27

1 Answers1

8

What you’re seeing is still rounding, it’s just not the rounding you’re expecting. Python by default rounds ties to even, instead of always rounding up, because rounding up on ties creates specific biases in the data (so does rounding ties to even, but these biases are less problematic, as they don’t affect the overall distribution).

As an example:

nums = [1.5, 2.5, 3.5, 4.5]
[round(x) for x in nums]
# [2, 2, 4, 4]

The same is true for more decimal points:

nums = [0.25, 0.75]
[round(x, 1) for x in nums]
# [0.2, 0.8]

Including 0.05, 0.15 … in the list above would yield surprising results, since these decimal floating-point values can’t be exactly represented as binary floating-point values, so they’re not exactly even; for example, 0.05 is stored as approximately 0.05000000000000000278…, so it won’t be rounded down to (even) 0.0, but rather up, to (odd) 0.1.

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214