The Wayback Machine - https://web.archive.org/web/20250413025224/https://github.com/python/cpython/issues/113804
Skip to content

Support formatting floats in hexadecimal (and binary?) notation #113804

Closed as not planned
@skirpichev

Description

@skirpichev

Feature or enhancement

Proposal:

Currently there is the float.hex() method to get a representation of a floating-point number as a hexadecimal string.

We can also (instead?) add same formating option for the str.format(), f-strings and old-style ('%' operator) string formatting. The C printf() has a dedicated type fields for this: 'a' and 'A'. (Printed values have mandatory 0x or OX prefix and alternate form is used to enforce decimal point.)

While it's possible to add such formatting types for the str.format() as well, for the old-style string formatting these letters will conflict (see this) with the ascii() conversion type. Lets instead reuse 'x' and 'X' type fields for this, currently supported only for integers.

This proposal introduce an incompatibility with C-style printf(), but some other languages also have such one. Notable example is the Go's fmt package.

New interface for formatting of floats will be more flexible and compact than the former float.hex():

>>> f'{-0.1:#x}'
'-0x1.999999999999ap-4'
>>> (-0.1).hex()
'-0x1.999999999999ap-4'
>>> f'{3.14159:+#X}'
'+0X1.921F9F01B866EP+1'
>>> f'{3.14159:.3x}'
'1.922p+1'

We may also consider to support printing floats as binary strings. Either in the base-2 scientific notation, or like the Go's strconv.FormatFloat. The gmpy2 (and MPFR library) uses "b"/"B" format types for this:

>>> format(gmpy2.mpfr(3.14), "b")
'1.1001000111101011100001010001111010111000010100011111p+1'

Related issue: #114667

Has this already been discussed elsewhere?

I have already discussed this feature proposal on Discourse

Links to previous discussion of this feature:

https://discuss.python.org/t/41848

Linked PRs

Metadata

Metadata

Assignees

No one assigned

    Labels

    type-featureA feature request or enhancement

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions