How do I get a decimal value when using the division operator in Python?

前端 未结 13 1880
旧巷少年郎
旧巷少年郎 2020-12-01 06:18

For example, the standard division symbol \'/\' rounds to zero:

>>> 4 / 100
0

However, I want it to return 0.04. What do I use?

相关标签:
13条回答
  • 2020-12-01 06:46

    Other answers suggest how to get a floating-point value. While this wlil be close to what you want, it won't be exact:

    >>> 0.4/100.
    0.0040000000000000001
    

    If you actually want a decimal value, do this:

    >>> import decimal
    >>> decimal.Decimal('4') / decimal.Decimal('100')
    Decimal("0.04")
    

    That will give you an object that properly knows that 4 / 100 in base 10 is "0.04". Floating-point numbers are actually in base 2, i.e. binary, not decimal.

    0 讨论(0)
提交回复
热议问题