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

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

>>> 4 / 100
0

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

This question is related to python python-2.7 math syntax operators

The answer is


Here we have two possible cases given below

from __future__ import division

print(4/100)
print(4//100)

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

4.0/100.0


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


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.


Import division from future library like this:

from__future__ import division

A simple route 4 / 100.0

or

4.0 / 100


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

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

Try 4.0/100


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

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.


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.


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

Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to python-2.7

Numpy, multiply array with scalar Not able to install Python packages [SSL: TLSV1_ALERT_PROTOCOL_VERSION] How to create a new text file using Python Could not find a version that satisfies the requirement tensorflow Python: Pandas pd.read_excel giving ImportError: Install xlrd >= 0.9.0 for Excel support Display/Print one column from a DataFrame of Series in Pandas How to calculate 1st and 3rd quartiles? How can I read pdf in python? How to completely uninstall python 2.7.13 on Ubuntu 16.04 Check key exist in python dict

Examples related to math

How to do perspective fixing? How to pad a string with leading zeros in Python 3 How can I use "e" (Euler's number) and power operation in python 2.7 numpy max vs amax vs maximum Efficiently getting all divisors of a given number Using atan2 to find angle between two vectors How to calculate percentage when old value is ZERO Finding square root without using sqrt function? Exponentiation in Python - should I prefer ** operator instead of math.pow and math.sqrt? How do I get the total number of unique pairs of a set in the database?

Examples related to syntax

What is the 'open' keyword in Swift? Check if returned value is not null and if so assign it, in one line, with one method call Inline for loop What does %>% function mean in R? R - " missing value where TRUE/FALSE needed " Printing variables in Python 3.4 How to replace multiple patterns at once with sed? What's the meaning of "=>" (an arrow formed from equals & greater than) in JavaScript? How can I fix MySQL error #1064? What do >> and << mean in Python?

Examples related to operators

What is the difference between i = i + 1 and i += 1 in a 'for' loop? Using OR operator in a jquery if statement What is <=> (the 'Spaceship' Operator) in PHP 7? What does question mark and dot operator ?. mean in C# 6.0? Boolean operators ( &&, -a, ||, -o ) in Bash PowerShell and the -contains operator How do I print the percent sign(%) in c Using the && operator in an if statement What do these operators mean (** , ^ , %, //)? How to check if div element is empty