简体   繁体   中英

How to format outputof floats so they have two places after decimal point?

this should be a very simple issue but I'm having a tougher time than expected on it. I want to have my floats be turned into strings but only to the 2nd decimal place. what I have works except with a few values that decide to extend more than 2 decimal points . Below is what im currently trying:

for i in range(len(self.monthlyData)):
        t = self.monthlyData[i] * 100
        '{0:.2}'.format(t)
        t = str(t) + " %"
        self.monthlyData[i] = t

I would want my values to be the decimals followed by the % sign. so I would want it to look like this "19.58 %" and like I said it works with most values but some values like 29.080000000000002 and stay like that.

The way I would do the task:

for i in range(len(self.monthlyData)):
    t = '{0:.2%}'.format(self.monthlyData[i])
    self.monthlyData[i] = t

But seriously, you do not have to loop through a pandas column to revise the values. A nicer approach would be the apply method with lambda :

self.monthlyData.apply(lambda x: '{0:.2%}'.format(x))

You can find more information at the official documentation

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM