How to get decimal value when using split operator in Python?

For example, the standard split character '/' is rounded to zero:

>>> 4 / 100 0 

However, I want it to return 0.04. What am i using?

+47
operators python syntax math
Sep 22 '08 at 20:06
source share
9 answers

There are three options:

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

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

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

You can also activate this behavior by passing the -Qnew argument to the -Qnew 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 need to use the // operator.

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

+100
Sep 22 '08 at 20:08
source share

Other answers show how to get a floating point value. Although this will be close to what you want, it will be inaccurate:

 >>> 0.4/100. 0.0040000000000000001 

If you really want a decimal value, do the following:

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

This will give you an object that correctly knows that 4/100 in the base is 10 "0.04". Floating point numbers are actually in base 2, i.e. Binary, not decimal.

+23
Sep 22 '08 at 21:12
source share

Make one or both of them a floating point number, for example:

 4.0/100.0 

Alternatively, include the feature that will be used by default in Python 3.0, the "true division", which does what you want. At the top of the module or script, do the following:

 from __future__ import division 
+7
Sep 22 '08 at 20:08
source share

You need to tell Python to use floating point values, not integers. You can do this simply by using the decimal point on the inputs:

 >>> 4/100.0 0.040000000000000001 
+3
Sep 22 '08 at 20:07
source share

You might want to look at the Python decimal package. This will provide good decimal results.

 >>> decimal.Decimal('4')/100 Decimal("0.04") 
+3
Sep 22 '08 at 21:38
source share

Try 4.0 / 100

+1
Sep 22 '08 at 20:07
source share

Simple route 4 / 100.0

or

4.0 / 100

+1
Sep 22 '08 at 20:07
source share

You cannot get a decimal value by dividing one integer by another, you still get an integer (the result will be truncated to an integer). You need at least one decimal value.

0
Sep 22 '08 at 20:11
source share

Please consider the following example.

 float tot=(float)31/7; 
-2
May 27 '15 at 6:16
source share



All Articles