[Python] Why does decimal.Context.create_decimal_from_float() not round near-zero values?

Discussão em 'Python' iniciado por Stack, Setembro 16, 2025.

  1. Stack

    Stack Membro Participativo

    Contrary to what the docs might suggest, create_decimal_from_float() does not always round to its specified precision. As the last line of the following example shows, when a near-zero value is passed as an argument, it does not get clamped. I would expect it to get rounded to zero.

    >>> import decimal
    >>> decimal.getcontext().prec = 6
    >>> decimal.getcontext().create_decimal_from_float(0.123456789123456789)
    Decimal('0.123457')
    >>> decimal.getcontext().create_decimal_from_float(0.000000000000000001)
    Decimal('1.00000E-18')


    I have discovered this behavior while trying to convert the result of sinus of 180 degrees to a decimal and had a similar result.

    From my perspective, it looks like a bug. But is there something that I am missing? Is there any workaround to make sure the argument gets rounded properly?

    Used Python version is 3.10.

    Continue reading...

Compartilhe esta Página