Calculating percentages, subtracting a discount, adding a markup is a very common task.
The “Percents” library simplifies the work with percentages. To use it, all you need to do is import the Percent type
from percents import PercentNext, the idea is simple. For example, we have a sum of $1000, from which we need to subtract 38%.
1000 - Percent(38)
>>> 620In the same way we can add
1000 + Percent(38)
>>> 1380To take 38% from this amount, all you have to do is multiply the following
1000 * Percent(38)
>>> 380The type of data returned always matches the type of the original one
result = 1000.0 + Percent(38)
>>> 1380
type(result)
>>> floatresult = Decimal(1000) + Percent(38)
>>> 1380
type(result)
>>> DecimalEven for strings
result = '1000' + Percent(38)
>>> '1380'
type(result)
>>> strPercents can be compared to each other
percent1 = Percent(10)
percent2 = Percent(20)
assert percent2 != percent1
assert percent2 > percent1
assert percent1 < percent2
percent1 = Percent(10)
percent2 = Percent(10)
assert percent2 == percent1
assert percent2 >= percent1
assert percent1 <= percent2and with other numbers. In this case, the comparison is in terms of percentage points.
percent = Percent(10)
assert percent == 10
assert percent != 11
assert percent > 9
assert percent < 11
assert percent >= 10.0
assert percent <= 10.0The Percent type has two attributes
- Percent.value -- value in percentage points
- Percent.multiplier -- multiplier
percent = Percent(10)
percent.value
>>> 10
percent.multiplier
>>> 0.1