How to convert fraction to percent in Python?
Last Updated :
24 Jan, 2021
Fractions are a part of a whole commodity that can be expressed in the form of a numerator divided by the denominator. A fraction is of the form , where p<=q.
There are various methods of converting between fractions and percentages.
Method 1:
Manual conversion of the fraction to percentage can be done by multiplying the rational number by 100. The obtained decimal number may be rounded up to the required number of digits by using the inbuilt math.round() function which has the following syntax:
round(number, digits)
Python3
num = 1 / 3
dec_num = num * 100
print ( "Decimal equivalent in %" )
print ( round (dec_num, 2 ))
|
Output
Decimal equivalent in %
33.33
In case the numerator is absolutely divisible by denominator, the number is returned to 1 place of decimal.
Python3
num = 2 / 4
dec_num = num * 100
print ( "Decimal equivalent in %" )
print ( round (dec_num, 4 ))
|
Output
Decimal equivalent in %
50.0
Method 2:
The str.format() method is used to convert the number into a percentage, by specifying the number of digits to take after the decimal point.
"{:.n%}".format(num)
- n represents the number of digits after the decimal point
- num represents the floating-point number expressed either as a decimal or a fraction
The special case where the denominator of the fraction is 1, that is, fractional numbers become equivalent to an integer value.
Python3
integer_num = 2
print ( "Converting number to percentage rounding to 0 place of decimal" )
print ( "{:.0%}" . format (integer_num))
integer_num = - 7
print ( "Converting number to percentage rounding to 5 place of decimal" )
print ( "{:.5%}" . format (integer_num))
|
Output
Converting number to percentage rounding to 0 place of decimal
Python3
integer_num = 2
print ( "Converting number to percentage rounding to 0 place of decimal" )
print ( "{:.0%}" . format (integer_num))
integer_num = - 7
print ( "Converting number to percentage rounding to 5 place of decimal" )
print ( "{:.5%}" . format (integer_num))
|
200%
Converting number to percentage rounding to 0 place of decimal
-700.00000%
While converting integers, the number of decimal places does not play any role, since the number is directly multiplied by 100. The number of zeros appended to the number is equivalent to the number of decimal places chosen.
The following Python code is used to convert a rational number to an equivalent percentage :
Python3
num = 1 / 3
print ( "Converting number to percentage rounding to 0 place of decimal" )
print ( "{:.0%}" . format (num))
num = - 2 / 4
print ( "Converting number to percentage rounding to 2 place of decimal" )
print ( "{:.2%}" . format (num))
|
Output
Converting number to percentage rounding to 0 place of decimal
33%
Converting number to percentage rounding to 2 place of decimal
-50.00%
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...