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

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

    A simple route 4 / 100.0

    or

    4.0 / 100

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

    Import division from future library like this:

    from__future__ import division
    
    0 讨论(0)
  • 2020-12-01 06:24

    You could also try adding a ".0" at the end of the number.

    4.0/100.0

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

    It's only dropping the fractional part after decimal. Have you tried : 4.0 / 100

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

    Add the following function in your code with its callback.

    # Starting of the function
    def divide(number_one, number_two, decimal_place = 4):
        quotient = number_one/number_two
        remainder = number_one % number_two
        if remainder != 0:
            quotient_str = str(quotient)
            for loop in range(0, decimal_place):
                if loop == 0:
                    quotient_str += "."
                surplus_quotient = (remainder * 10) / number_two
                quotient_str += str(surplus_quotient)
                remainder = (remainder * 10) % number_two
                if remainder == 0:
                    break
            return float(quotient_str)
        else:
            return quotient
    #Ending of the function
    
    # Calling back the above function
    # Structure : divide(<divident>, <divisor>, <decimal place(optional)>)
    divide(1, 7, 10) # Output : 0.1428571428
    # OR
    divide(1, 7) # Output : 0.1428
    

    This function works on the basis of "Euclid Division Algorithm". This function is very useful if you don't want to import any external header files in your project.

    Syntex : divide([divident], [divisor], [decimal place(optional))

    Code : divide(1, 7, 10) OR divide(1, 7)

    Comment below for any queries.

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

    Make one or both of the terms a floating point number, like so:

    4.0/100.0
    

    Alternatively, turn on the feature that will be default in Python 3.0, 'true division', that does what you want. At the top of your module or script, do:

    from __future__ import division
    
    0 讨论(0)
提交回复
热议问题