0

I had experimented with some code on Python and I got strange results with :.2f.

>>> a = 4.34567
>>> a
4.34567
>>> f"{a:.2f}"
'4.35'
>>> "%.2f" % a
'4.35'
>>> "{:.2f}".format(a)
'4.35'
>

I expected results like:

>>> a = 4.34567
>>> a
4.34567
>>> f"{a:.2f}"
'4.34'
>>> "%.2f" % a
'4.34'
>>> "{:.2f}".format(a)
'4.34'
>

Also I getting strange results with other number (:.3f, ...) But I haven't seen strange results with :.5f

>>> f"{a:.3f}"
'4.346'
>>> f"{a:.f}"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: Format specifier missing precision
>>> f"{a:.4f}"
'4.3457'
>>> f"{a:.5f}"
'4.34567'

I seen this in Python 3.11.2 on Linux. I didn't tried to reproduce it on old python version. Is that bug or feature?

fmmaks
  • 1
  • 2
  • This is a feature! F-String always rounds the floats to their decimal places: Thats why 3.34567 = 3.45 – lotus Mar 27 '23 at 11:14
  • 1
    To get the float without rounding, you can use `str(a)[:n]`, with `n` being the number of decimal places + 2. For arbitrary `a`, it's a little less elegant with `str(a)[:math.log(a)+n]`. – B Remmelzwaal Mar 27 '23 at 11:15
  • Thanks! I already thought that I found bug. – fmmaks Mar 27 '23 at 11:27

1 Answers1

0

It's not a bug, but a feature. :.2f always rounds output. To print float without rounding You need to use str(a)[:n], where a is float and n is count of digits

fmmaks
  • 1
  • 2
  • 1
    _"n is count of digits"_ - That's going to be off by one. You need to slice an additional index to include the decimal point. – B Remmelzwaal Mar 27 '23 at 11:25