Reputation: 5395
I'm learning via Learn Python The Hard Way and I've come across:
Notice the math seems “wrong”? There are no fractions, only whole numbers. Find out why by researching what a “floating point” number is.
I've read what it is on: http://docs.python.org/tutorial/floatingpoint.html
I can't figure out on how I can output floating point numbers, I've thought about using round(3 + 3, 2)
.
Is this right?
Upvotes: 9
Views: 52188
Reputation: 1
python console print(3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6) I get 7 but in pycharm I get 6.75.
Upvotes: 0
Reputation: 1
Any number with a decimal is a floating point number.
In python take the following example,
If you divide 11/4 the output will be 2 [here 11 is not a floating point number]
But if you divide 11.0/4, the output will be 2.75 [here 11.0 is a floating point number].
Upvotes: 0
Reputation: 285
For floating point numbers you write a period after the number, and a zero (if it's a whole number).
Like this:
1.0 <---- Floating point.
1 <------- integer
That is how python interprets them.
if my_answer != your_question:
print "I did not understand your question. Please rephrase it."
else:
print "Good luck. Python is fun."
I agree with rohit, the 0 is not needed. Although it makes things easier for beginners.
Upvotes: 8
Reputation: 11
Orange, read the last question in the lesson, the author gave you the answer
Why does / (divide) round down? It's not really rounding down; it's just dropping the fractional part after the decimal. Try doing 7.0 / 4.0 and compare it to 7 / 4 and you'll see the difference.
good luck
Upvotes: 1
Reputation: 131567
3 is an integer.
3.0 is a float.
>>> type(3)
<type 'int'>
>>> type(3.0)
<type 'float'>
round():
Round a number to a given precision in decimal digits (default 0 digits). This always returns a floating point number.
So that is why in your case, 6.0 is returned.
Upvotes: 2
Reputation: 7629
Agree with all of the answers above. You don't even need to put a zero after the period though.
For example:
In [1]: type(3)
Out[1]: <type 'int'>
In [2]: type(3.)
Out[2]: <type 'float'>
Upvotes: 1
Reputation: 798456
Passing a value to the float()
constructor will make it a float
if possible.
print float(2)
print float('4.5')
Use string interpolation or formatting to display them.
print '%.3f' % 4.53
Upvotes: 5