Converting from float to percentage

Question:

I would like to convert a decimal number (say 0.33333) to percentage (expected answer 33.33%)

I used the following

x = 0.3333

print(format(x,'.2%'))

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

Asked By: zaydar

||

Answers:

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.

class Percent(float):
    def __str__(self):
        return '{:.2%}'.format(self)
x = Percent(0.3333)
print(x)
# 33.33%

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:

def __repr__(self):
    return '{:.2%}'.format(self)
Answered By: Mehdi

I made it on a single line like:

x = 0.333
print(str(int(x*100)) + "%)
Answered By: VitorGRM
x = 0.3333

print('{:,.2%}'.format(x))  # Prints percentage format, retains x as float variable

Output:

33.33%
Answered By: DToelkes

Use f-strings! (python >= 3.6)

x = 0.3333

print(f"{x:,.2%}")

That is: print x, to 2 decimal places, and add the % symbol at the end. x is not altered by the f-string.

Answered By: vtnate
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.