I would like to convert a decimal number (say 0.33333) to percentage (expected answer 33.33%)
I used the following
JavaScript
x
4
1
x = 0.3333
2
3
print(format(x,'.2%'))
4
which gives indeed 33.33%
However, the result is a string, I would like it to still be a number (in % format) to be able to perform mathematical operations on it (e.g. format(x,'.2%')*2
to give 66.66%
But this throws an exception as 33.33% is a string
Advertisement
Answer
An idea is to create a custom datatype, I’ll call it Percent
, which inherit everything from float
, but when you want to use it as a string it shows a %
and multiplies the number with 100.
JavaScript
1
7
1
class Percent(float):
2
def __str__(self):
3
return '{:.2%}'.format(self)
4
x = Percent(0.3333)
5
print(x)
6
# 33.33%
7
If you want to represnt the value in envoirment like jupyter notebook in your format you can add same method with the name __repr__
to Percent Class:
JavaScript
1
3
1
def __repr__(self):
2
return '{:.2%}'.format(self)
3