Skip to content

Types f and e in format spec does not remove trailing zeros for floats if precision is not specified #111125

Closed as not planned
@Prometheus3375

Description

@Prometheus3375

Bug report

Bug description:

I will report this as a bug, however, this can be an issue with documentation.

By the docs of format specification mini-language:

'f' -- Fixed-point notation. For a given precision p, formats the number as a decimal number with exactly p digits following the decimal point. With no precision given, uses a precision of 6 digits after the decimal point for float, and uses a precision large enough to show all coefficient digits for Decimal. If no digits follow the decimal point, the decimal point is also removed unless the # option is used.

I am focusing on the bold part. Let's test it.

Integers, floats and complex numbers:

>>> f'{1:f}'
'1.000000'
>>> f'{1.:f}'
'1.000000'
>>> f'{1+1j:f}'
'1.000000+1.000000j'
>>> f'{.1:f}'
'0.100000'

Decimals:

>>> from decimal import Decimal
>>> f'{Decimal(1):f}'
'1'
>>> f'{Decimal(1.):f}'
'1'
>>> f'{Decimal(.1):f}'
'0.1000000000000000055511151231257827021181583404541015625'

If no digits follow the decimal point, the decimal point is also removed unless the # option is used.

The sentence goes after mentioning Decimal. So maybe the sentence speaks only about them? If so, then note about # must work.

>>> from decimal import Decimal
>>> d = Decimal(1)
>>> f'{d:#f}'
ValueError: invalid format string

As intended, because per # documentation:

The '#' option causes the “alternate form” to be used for the conversion. The alternate form is defined differently for different types. This option is only valid for integer, float and complex types

The further docs of # also suggest that f must remove trailing zeros:

For float and complex the alternate form causes the result of the conversion to always contain a decimal-point character, even if no digits follow it. Normally, a decimal-point character appears in the result of these conversions only if a digit follows it. In addition, for 'g' and 'G' conversions, trailing zeros are not removed from the result.

The same issue is true for format types e, F and E.

CPython versions tested on:

3.11

Operating systems tested on:

Windows

Metadata

Metadata

Assignees

No one assigned

    Labels

    type-bugAn unexpected behavior, bug, or error

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions