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

前端 未结 13 1881
旧巷少年郎
旧巷少年郎 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:32

    Try 4.0/100

    0 讨论(0)
  • 2020-12-01 06:34

    You might want to look at Python's decimal package, also. This will provide nice decimal results.

    >>> decimal.Decimal('4')/100
    Decimal("0.04")
    
    0 讨论(0)
  • 2020-12-01 06:35

    There are three options:

    >>> 4 / float(100)
    0.04
    >>> 4 / 100.0
    0.04
    

    which is the same behavior as the C, C++, Java etc, or

    >>> from __future__ import division
    >>> 4 / 100
    0.04
    

    You can also activate this behavior by passing the argument -Qnew to the Python interpreter:

    $ python -Qnew
    >>> 4 / 100
    0.04
    

    The second option will be the default in Python 3.0. If you want to have the old integer division, you have to use the // operator.

    Edit: added section about -Qnew, thanks to ΤΖΩΤΖΙΟΥ!

    0 讨论(0)
  • 2020-12-01 06:37

    Here we have two possible cases given below

    from __future__ import division
    
    print(4/100)
    print(4//100)
    
    0 讨论(0)
  • 2020-12-01 06:40

    You need to tell Python to use floating point values, not integers. You can do that simply by using a decimal point yourself in the inputs:

    >>> 4/100.0
    0.040000000000000001
    
    0 讨论(0)
  • 2020-12-01 06:41

    You cant get a decimal value by dividing one integer with another, you'll allways get an integer that way (result truncated to integer). You need at least one value to be a decimal number.

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