yoshiserry
yoshiserry

Reputation: 21345

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

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?

Upvotes: 1

Views: 14264

Answers (3)

J. Khoury
J. Khoury

Reputation: 679

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

Upvotes: 1

Andy Hayden
Andy Hayden

Reputation: 375505

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

Upvotes: 3

user2357112
user2357112

Reputation: 280788

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.

Upvotes: 4

Related Questions