Rounding Float Number to the Nearest Tenth

Hi i have a number like 1.3333333333(THE RESULT OF PYTHON DIVISION) to round of to the nearest tenth

Input

1.333333333

Output

1.34 or 1.3

Here is what i tried

    def round(self,oj):
        try:
            (bd,ad) = oj.split(".")
            if int(ad[1]) >5:
                up = True   
            else:
                up= False
            if up:
                if ad[0]==9:
                    oj = str(int(bd)+1)
                
                else:
                    oj = str(bd)+"."+str(int(ad[0])+1)
            else:
                oj =str( bd)+"."+ad[0]
        except IndexError:
            pass
        
        return float(oj)    
        

But i believe there is a better way to do it so please tell any suggestions you have

6

1 Answer

There are several ways you can round the number in python.

1) Use the round() function.

round(1.33333, 1) #return float

Output: 1.3

2) Use the format() function.

"{0:.1f}".format(1.33333) #return string

Output: 1.3

3) Use a format-string with the "%" operator

"%.1f" % 1.333333 #return string

Output: 1.3

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

James H. Sterling

James H. Sterling

Environmental Science & Climate Journalist

James Sterling reports on renewable energy developments, climate policy, ecological conservation, and green tech innovations around the globe.

Share this article
Twitter Facebook Pinterest