9

Consider:

>>> numerator = 29
>>> denom = 1009
>>> print str(float(numerator/denom))
0.0

How do I make it return a decimal?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
TIMEX
  • 259,804
  • 351
  • 777
  • 1,080
  • 1
    Somewhat an aside, but `float` is not the same as the `Decimal` type in the Python standard library. When you say "I just want it to return a decimal" what you really mean is "I just want it to return a string representing a fractional value in decimal notation", right? – Daniel Pryden Nov 24 '09 at 01:38

4 Answers4

30

Until version 3, Python's division operator, /, behaved like C's division operator when presented with two integer arguments: it returns an integer result that's truncated down when there would be a fractional part. See: PEP 238

>>> n = 29
>>> d = 1009
>>> print str(float(n)/d)
0.0287413280476

In Python 2 (and maybe earlier) you could use:

>>> from __future__ import division
>>> n/d
0.028741328047571853
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
miku
  • 181,842
  • 47
  • 306
  • 310
  • -7//3 = -3 (remainder is = 2) in Python and -7/3 = -2 (remainder = -1) in C/C++ so I would not say this behavior is the same in Python as in C/C++ – Artur May 17 '17 at 09:51
  • @Artur That's the difference between floored division vs standard divison, and modulus vs remainder operators. Floor and mod work towards negative infinity, standard division and remainder work toward zero. – Aaron Franke May 19 '18 at 06:45
8

In Python 2.x, division works like it does in C-like languages: if both arguments are integers, the result is truncated to an integer, so 29/1009 is 0. 0 as a float is 0.0. To fix it, cast to a float before dividing:

print str(float(numerator)/denominator)

In Python 3.x, the division acts more naturally, so you'll get the correct mathematical result (within floating-point error).

Adam Rosenfield
  • 390,455
  • 97
  • 512
  • 589
1

In your evaluation you are casting the result, you need to instead cast the operands.

Recursion
  • 2,915
  • 8
  • 38
  • 51
0
print str(float(numerator)/float(denom))
inspectorG4dget
  • 110,290
  • 27
  • 149
  • 241
  • It's sufficient to cast either of the operands to float(). I generally recommend casting the numerator as it locates the cast at the beginning of the expression where readers will normally see it more readily. – Jim Dennis Nov 24 '09 at 05:55
  • Yes it is, but this seemed more "proper" to me just because it was more transparent in its casting. But yes, casting one alone is enough. – inspectorG4dget Nov 24 '09 at 06:59