Textual formatting of floating point numbers

assert f"{385.0:.2}" == "3.9e+02" # FAILS
assert f"{385.1:.2}" == "3.9e+02" # passes
assert f"{385.01:.2}" == "3.9e+02" # passes
assert f"{385.000000004:.2}" == "3.9e+02" # passes

Why is this the current python behavior? Is this related to IEEE floating point bit representations? Should this not be a bug?

The problem is 385.0 being rounded to two decimals equalling 380 rather than 39

This is pretty standard rounding for IEEE floating point. “Banker’s rounding” rounds to the nearest even number. This method reduces the cumulative error when adding rounded numbers together.

2 Likes

It is intentional, as explained here: Built-in Functions — Python 3.13.5 documentation and links following. If you want more control, there’s the decimal module.

Thanks! The documentation explicitly calls this out