How do you get the decimal in python?

In a truly surreal experience, I spent 20 minutes on a task that I thought would take 20 seconds.

I want to use decimal places with 3 or more places. I cannot get anything in one place, and even then it is nonsense.

For example, I cannot get 1/3 to display as nothing but 0 or 0.0 .

Googling led me to Decimal, but Decimal didn't help either.

Please stop this torture and tell me what I need to do to make 1/3 appear as .333 !

Change Thank you for understanding! Apparently, computer scientists have invented something called integer division to confuse and annoy mathematicians. Thank you for being kind enough to dispel my confusion.

+8
python
source share
5 answers

In Python 2, 1/3 performs integer division since both operands are integers. You need to do a float separation:

 1.0/3.0 

Or:

 from __future__ import division 

This will do / real division and // do integer division. This is the default value for Python 3.

+17
source share

If you divide 2 integers, you will get the result with a truncated integer (i.e. any fractional part of the result will be discarded), therefore

  1 / 3 

gives you:

  0 

To avoid this problem, at least one of the operands must be floating. for example, 1.0 / 3 or 1 / 3.0 or (of course) 1.0 / 3.0 will avoid whole truncation . This behavior is not unique to Python.

( Edit : as @Ivc mentioned in the helpful comment below, if one of the integer operands is negative, the result is floor () 'ed - see this article for the reason for this).

In addition, there may be some confusion in the internal and external representation of the number. A number is what it is, but we can determine how it was displayed.

You can control the appearance using formatting instructions. For example, a number can be displayed with 5 digits after the decimal point as follows:

 n = 1/3.0 print '%.5f' %n 0.33333 

To get 15 digits after a decimal number.

 print '%.15f' %n 0.333333333333333 

Finally, there is a โ€œnew and improvedโ€ way to format strings / numbers using the .format() function, which will probably be around a lot longer than the % format shown above. An example is:

 print 'the number is {:.2}'.format(1.0/3.0) 

will provide you with:

 the number is 0.33 
+7
source share

Your value must be a floating point

 In [1]: 1/3 Out[1]: 0 In [2]: 1/3.0 Out[2]: 0.33333333333333331 

or

 In [1]: from __future__ import division In [2]: 1/3 Out[2]: 0.33333333333333331 
+2
source share

In Python2, you need to specify at least one of the operands as a floating point number. To take only 3 decimal places, you can use the round() method:

 >>> a = 1.0 / 3 >>> round(a, 3) 0.333 

In Python3, it seems like they are not doing integer division by default, so you can do:

 >>> a = 1/3 >>> round(a, 3) 0.333 
+2
source share

Use decimal place. You can get 100 digits per dot.

 from decimal import * getcontext().prec = 100 Decimal(1)/Decimal(3) 
+1
source share

All Articles