[Python] How to limit numbers after comma using Decimal?

Discussão em 'Python' iniciado por Stack, Abril 13, 2025.

  1. Stack

    Stack Membro Participativo

    I have a number from database (Clickhouse), and this number is limited with only two digits after comma on the database level. So I always have something like 34.23, 2323.23, 324234.3, and so one (in our region we use dot to split fractional part of number).

    And I have to multiply that number hardcoded numbers like 1.22, 1.24, or 1.25 and to return also a Decimal number with only two digits. Here how it looks like (simplified with no if-blocks and other logic):

    import decimal
    TAX_22 = decimal.Decimal('1.22')

    def wrap_on_tax(item):
    return item.money * TAX_22


    But for this code I going to get a result 285.7362 for money=234.21. And I want to get 285.73.

    And I'm trying to find out most clear and pythonic way to do this.

    Sure, I can just do a thing like this:

    import decimal
    TAX_22 = decimal.Decimal('1.22')

    def wrap_on_tax(item):
    return decimal.Decimal('%.2f' % item.money * TAX_22)


    And this approach will give me what I want. But typecasting a number to a string to get a number again doesn't look perfectly clear. I've tried to find any argument for Decimal constructor to tell it how many digits after comma I want, but I can't find anything.

    Is there any more elegant way to get what I'm trying to get?

    Continue reading...

Compartilhe esta Página