How to get decimal division in python3?

I am looking for a Python way to get the remainder of the decimal division.

My use case is here, I want to send one price to several products. For example, I received an order of $ 10 with 3 points, and I want to send the price of 3 products without losing a cent :)

And since this is the price, I want only 2 decimal places.

So far, here is the solution I found:

from decimal import Decimal

twoplaces = Decimal('0.01')

price = Decimal('10')
number_of_product = Decimal('3')

price_per_product = price / number_of_product

# Round up the price to 2 decimals
# Here price_per_product = 3.33 
price_per_product = price_per_product.quantize(twoplaces)

remainder = price - (price_per_product * number_of_product)
# remainder = 0.01

I would like to know if there is a more pythonic way to do this, for example, for an integer:

price = 10
number_of_product = 3

price_per_product = int(price / number_of_product)
# price_per_product = 3
remainder = price % number_of_product 
# remainder = 1

Thank!

+4
source share
1 answer

Convert to cents, multiplying your prices by 100, do all your math in cents, and then convert back.

price = 10
number_of_product = 3

price_cents = price * 100

price_per_product = int(price_cents / number_of_product) / 100
# price_per_product = 3
remainder = (price_cents % number_of_product) / 100
# remainder = 1

Then use Decimal to convert to strings.

+4
source

Source: https://habr.com/ru/post/1680180/


All Articles