Reputation: 83
I'm just starting to learn Python (2.7) and I have a question.
First my code:
def add(a, b):
print "ADDING %d + %d" % (a, b)
return a + b
number_a = float(raw_input())
number_b = float(raw_input())
add(number_a, number_b)
As you can see I want to ask the user to give me 2 floating numbers and then add them and print the solution. But when I put in 2 floating numbers, they are still printed as rounded numbers. How do I get this right?
Upvotes: 0
Views: 104
Reputation: 3831
Use %f
for floats. You can adjust decimal precision using %.2f
for 2 digits or %.3f
for three digits, etc.
def add(a, b):
print "ADDING %.2f + %.2f" % (a, b)
return a + b
number_a = float(raw_input())
number_b = float(raw_input())
add(number_a, number_b)
Upvotes: 2
Reputation: 133724
def add(a, b):
print "ADDING {0} + {1}".format(a, b)
return a + b
>>> add(1, 2)
ADDING 1 + 2
3
>>> add(1.5, 3)
ADDING 1.5 + 3
4.5
Upvotes: 0
Reputation: 26204
You have to use formatting sequence for floats, not integers, so this:
print "ADDING %d + %d" % (a, b)
should be:
print "ADDING %f + %f" % (a, b)
Upvotes: 0
Reputation: 97671
%d
formats a decimal integer. %f
formats a float:
def add(a, b):
print "ADDING %f + %f" % (a, b)
return a + b
Upvotes: 2