format number (based on calculation) as a percentage to two decimal places using python

10,581

Solution 1

You forgot to make a string:

format_percent = '{:.2f}'.format(percent_val)
#                ^      ^

Also, if you want a percent, you'll need to multiply by 100, and if you're on Python 2 (I can't tell), you'll either need to use floats or from __future__ import division.

If you want to round the number to two decimal places, rather than creating formatted output, there's the round function:

rounded = round(percent_val, 2)

Then your output will be a float instead of a string, and you can keep doing math with it.

Solution 2

You can plug the display format into pandas' display options:

In [11]: df = pd.DataFrame(np.random.randn(2, 2))

In [12]: df
Out[12]:
          0         1
0  1.058814 -0.011675
1 -0.002627 -0.152505

In [13]: pd.options.display.float_format = '{:.2f}'.format

In [14]: df
Out[14]:
      0     1
0  1.06 -0.01
1 -0.00 -0.15

See more about python's string formatting here.

Note: the numbers themselves are unaffected (they haven't been rounded):

In [15]: df.iloc[0, 0]
Out[15]: 1.058814403984879

Solution 3

In the event you decide to use pandas and df, here is a quick method if you don't mind having all your pd data set to a specific precision, and as you can see the data can still be used with its original precision.

import pandas as pd
import numpy as np

pd.set_option('precision',2)
df = pd.DataFrame(np.random.randn(5,2), columns = ['A','B'])
df
Out[15]: 
      A     B
0 -1.87  1.20
1 -0.55 -1.19
2  1.04  0.89
3 -0.65  0.30
4  0.07 -1.37

df.A[0] + 1.77777
Out[16]: -0.095449113301297794
Share:
10,581
yoshiserry
Author by

yoshiserry

Updated on June 04, 2022

Comments

  • yoshiserry
    yoshiserry almost 2 years

    The values: budget = 11,000 actual = 10,000 variance = budget - actual (1,000)

    total, would be the value of budget variable: 11,000
    

    My Code:

    percent_val = variance/total
    format_percent = {:.2f}.format(percent_val)
    return format_percent
    

    I Thought the above code would retun the value 9.09 (at two decimal places)

    return value: 9.09
    

    This video shows it, but I can't see to get it to work using the {0:2.df} string?

    http://www.youtube.com/watch?v=mmJPx6YsOMI
    

    HOW DO I format the 9.09 percent as a number and not a string so I can do calculations with it later?

  • yoshiserry
    yoshiserry about 10 years
    If I do as you suggested it returns a string, I want it to be a number (I want to use it for calculations).
  • user2357112
    user2357112 about 10 years
    @yoshiserry: If you want a number, keep percent_val. format_percent is a string. Do the math with numbers, and convert to strings for display purposes.
  • yoshiserry
    yoshiserry about 10 years
    how do I do that if I want to do this with columns in a pandas dataframe? I have the budget, actual, and percentage values, and I want to calculate the variance% value - but keep it as a number!.
  • user2357112
    user2357112 about 10 years
    @yoshiserry: Dunno. I'm not familiar with Pandas.
  • yoshiserry
    yoshiserry about 10 years
    Forgetting pandas for a minute, I find it hard to believe you can't format a number to 2dp, you can only do that if you format a string.
  • user2357112
    user2357112 about 10 years
    @yoshiserry: Numbers are numbers. They have no concept of how they're displayed. Their job is math. If you want to round a number to two decimal places, there's the round function for that.
  • yoshiserry
    yoshiserry about 10 years
    doesn't the ROUND function, and the .FORMAT function do the same thing?
  • Andy Hayden
    Andy Hayden about 10 years
    @yoshiserry round actually changes the numbers (how they're stored), format just changes the way they are printed.
  • yoshiserry
    yoshiserry about 10 years
    @AndyHayden All I want to do is add two columns to a dataframe in pandas: col 1 - varaince (buget - actual) and 2 variance percent column which formats the value to 2dp (e.g. 9.09)
  • yoshiserry
    yoshiserry about 10 years
    And can you apply it to selected columns, instead of the whole dataframe? - because If I have a text column like someones name, I can foresee it throwing an error?
  • Andy Hayden
    Andy Hayden about 10 years
    text columns are unaffected, it's only for floats. Not sure if you can do it per column