How to convert fraction to percent in Python?
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.
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course
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:
Decimal equivalent in % 33.33
In case the numerator is absolutely divisible by denominator, the number is returned to 1 place of decimal.
Decimal equivalent in % 50.0
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 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.
Converting number to percentage rounding to 0 place of decimal
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 :
Converting number to percentage rounding to 0 place of decimal 33% Converting number to percentage rounding to 2 place of decimal -50.00%