new_to_code
new_to_code

Reputation: 37

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

Upvotes: 0

Views: 1249

Answers (1)

Moisés Cunha
Moisés Cunha

Reputation: 141

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

Upvotes: 2

Related Questions