[Python] string format a Decimal instance using an underscore as a thousands separator?

Discussão em 'Python' iniciado por Stack, Março 5, 2025.

  1. Stack

    Stack Membro Participativo

    I can easily do this for floats using an f-string like this:

    x = float(123456789.123456)
    print(f"{x:_f}")


    prints 123_456_789.123456 exactly as expected.

    But if try the same technique for a Decimal

    from decimal import Decimal
    x = Decimal("123456789.123456")
    print(f"{x:_f}")


    this code crashes with ValueError: invalid format string

    What?

    Does Decimal only partly support Python's Format Specification Mini-Language?

    Is this a known bug with Decimal?

    This is especially strange because Decimal does support underscore as a thousands separator when parsing FROM a string:

    from decimal import Decimal
    x = Decimal("123_456_789.123456")
    print(f"{x:f}")


    prints 123456789.123456 exactly as expected.

    Is this there another way that I can do this?

    Continue reading...

Compartilhe esta Página