Convert percentage to float python

I wrote the following method that should always return the output to the exact same accuracy as the input, with no floating point errors such as in the other answers.

def percent_to_float(s):
    s = str(float(s.rstrip("%")))
    i = s.find(".")
    if i == -1:
        return int(s) / 100
    if s.startswith("-"):
        return -percent_to_float(s.lstrip("-"))
    s = s.replace(".", "")
    i -= 2
    if i < 0:
        return float("." + "0" * abs(i) + s)
    else:
        return float(s[:i] + "." + s[i:])

Explanation

  1. Strip the "%" from the end.
  2. If percent has no ".", simply return it divided by 100.
  3. If percent is negative, strip the "-" and re-call function, then convert the result back to a negative and return it.
  4. Remove the decimal place.
  5. Decrement i (the index the decimal place was at) by 2, because we want to shift the decimal place 2 spaces to the left.
  6. If i is negative, then we need to pad with zeros.
    • Example: Suppose the input is "1.33%". To be able to shift the decimal place 2 spaces to the left, we would need to pad with a zero.
  7. Convert to a float.

Test case (Try it online):

from unittest.case import TestCase

class ParsePercentCase(TestCase):
    tests = {
        "150%"              : 1.5,
        "100%"              : 1,
        "99%"               : 0.99,
        "99.999%"           : 0.99999,
        "99.5%"             : 0.995,
        "95%"               : 0.95,
        "90%"               : 0.9,
        "50%"               : 0.5,
        "66.666%"           : 0.66666,
        "42%"               : 0.42,
        "20.5%"             : 0.205,
        "20%"               : 0.2,
        "10%"               : 0.1,
        "3.141592653589793%": 0.03141592653589793,
        "1%"                : 0.01,
        "0.1%"              : 0.001,
        "0.01%"             : 0.0001,
        "0%"                : 0,
    }
    tests = sorted(tests.items(), key=lambda x: -x[1])

    def test_parse_percent(self):
        for percent_str, expected in self.tests:
            parsed = percent_to_float(percent_str)
            self.assertEqual(expected, parsed, percent_str)

    def test_parse_percent_negative(self):
        negative_tests = [("-" + s, -f) for s, f in self.tests]
        for percent_str, expected in negative_tests:
            parsed = percent_to_float(percent_str)
            self.assertEqual(expected, parsed, percent_str)

How do you convert a string representing a percentage number into an actual number that can be used to perform calculations?

To convert a string represented as a percentage number into an actual decimal number in Python use the built-in float() function after removing the percent symbol from the string and any other characters that prevent numeric conversion.

Without purging from the original string the percent symbol you will get a ValueError as demonstrated below in the Python REPL:

>>> float("30.0%")
Traceback (most recent call last):
File "", line 1, in
ValueError: could not convert string to f
loat: '30.0%'

So to get the conversion to work well you need to remove characters from the original string this would include the percent symbol.

Here’s an example demonstrating the use of the float function and how you can use the built-in replace() string method to strip the percentage symbol away:

>>> float("30.0%".replace("%", ""))
30.0

As you can see from the above example you can extract the number from the original percentage string.

Now that you have a number to convert the percentage number into its decimal representation simply divide by 100.

Here’s how you could write the above in one neat little line of code:

>>> float("30.0%".replace("%", ""))/100
0.3

This is the easiest way to convert a string number with a percentage symbol.

However, there may be times other characters need to be removed to help with the conversion.

Convert Percent String Number With Comma

Another character that may prevent proper conversion of the percent string number is if the string contains a comma.

Here’s an example demonstrating the previous conversion, but using it on a string percentage number with a comma, once again you will get the all-too-familiar ValueError:

>>> float("3,000%".replace("%", ""))
Traceback (most recent call last):
File "", line 1, in
ValueError: could not convert string to float: '3,000.0'

Therefore, besides removing the actual % symbol, should your percentage string numbers contain commas you may need to remove that too.

Thankfully, it’s not too difficult to remove additional characters from your original string but if you still want to use the replace string method you will need to chain them together like so:

>>> float("3,000%".replace("%", "").replace(",", ""))/100
30.0

As you can see from the above example the Python code output the intended result of 30 from a percentage string number containing a comma.

Remove All Non-Numeric Characters

An easier way to manage the removal of all characters that may prove problematic with the string conversion is to just remove everything except for the numbers and the decimal place characters.

The best way to handle this type of operation is to import the Regular Expression (Regex for short) library and to use the substitute function.

The substitute function takes three parameters with the first being the regex pattern to match, the second parameter what string to substitute and third the string to operate on.

Here’s one way you could strip all the numbers out using the Regex library:

>>> import re
>>> float(re.sub(r"[^0-9.]", "", "3,000.0%"))/100
30.0

From the above code you can see the Regex library needs to be imported first and then you perform the substitution of all non-numeric and decimal place characters from the percent string.

The Regex pattern that handles this is seen in the first parameter of the sub() function r"[^0-9.]" which means that the substitution will happen on all characters not between 0 to 9 and the decimal dot character. Therefore every other character is substituted with a blank character (meaning it’s removed).

Summary

To convert a percentage string to a decimal number use the built in function float with the replace string methods like so: float("30.0%".replace("%", ""))/100.

If the percentage string contains other characters preventing conversion you may want to import the Regex library and use the sub method like so: float(re.sub(r"[^0-9.]", "", "3,000%"))/100.

How do you convert percentage to float?

To convert a percentage string to a decimal number use the built in function float with the replace string methods like so: float("30.0%". replace("%", ""))/100 . If the percentage string contains other characters preventing conversion you may want to import the Regex library and use the sub method like so: float(re.

How do you convert a percentage in Python?

How to format a number as a percentage in Python.
a_number = 0.20..
percentage = "{:.0%}". format(a_number).
print(percentage).

How do I remove a percentage from a Dataframe in Python?

str. rstrip() method to remove the trailing '%' character and then use astype(float) to convert it to numeric. You can also use Series. str.

How do I remove a percentage from a column in Python?

First of all, create a data frame with a column having percent sign at last position in every value. Then, use gsub function to remove the percent sign at last position from every value in the column.