Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rounding floats to nearest 10th

Tags:

python

I am trying to round an equation of two float numbers but it outputs without the decimals, it just rounds it to the nearest number for example 21.3 to 21. When I put ", 2" which should set it to round to the nearest 10th.

New code:

def add(op1,op2):
    result = int(round(op1 + op2, -1))
    print("")
    print ("Output: %d + %d = %d" % (op1, op2, result))

Output:

Output: 10 + 10 = 20

NEW

Output:

Output: 10.3 + 10.9 = 21.0

Code:

def add(op1,op2):
    result = int(round(op1 + op2, 1))
    print("")
    print ("Output: %0.1f + %0.1f = %0.1f" % (op1, op2, result))
like image 964
user2839430 Avatar asked Oct 17 '13 16:10

user2839430


1 Answers

Here's how to round a number to the nearest tenth:

>>> round(21.3331, 1)
21.3

Here's how to print out a floating point number with one decimal point:

>>> print "%.1f" % (21.3331,)
21.3

Note that if you do it using %d it will get printed as rounded to the nearest integer:

>>> print "%d" % (21.3331,)
21

See the String Formatting Operations docs for more on how the % formatting works.

like image 122
Claudiu Avatar answered Oct 28 '22 04:10

Claudiu