I have an app that has some complex mathematical operations leading to very small amount in results like 0.000028 etc. Now If I perform some calculation in javascript like (29631/1073741824) it gives me result as 0.000027596019208431244 whereas the same calculation in python with data type float gives me 0.0. How can I increase the number of decimal points in results in python
Asked
Active
Viewed 227 times
0
-
2Use `decimal`: https://docs.python.org/3.6/library/decimal.html, where arbitrary precision can be set. – jOOsko Jun 21 '17 at 11:39
2 Answers
5
The problem is not in a lack of decimal points, it's that in Python 2 integer division produces an integer result. This means that 29631/1073741824 yields 0 rather than the float you are expecting. To work around this, you can use a float for either operand:
>>> 29631.0/1073741824
2.7596019208431244e-05
This changed in Python 3, where the division operator does the expected thing. You can use a from __future__
import to turn on the new behavior in Python 2:
>>> from __future__ import division
>>> 29631/1073741824
2.7596019208431244e-05

user4815162342
- 141,790
- 18
- 296
- 355
-1
If you're using Python 3.x, you should try this :
print(str(float(29631)/1073741824))

RyanU
- 128
- 1
- 8
-
1In Python 3 that should not be necessary, as `29631/1073741824` will calculate the expected (float) result. – user4815162342 Jun 21 '17 at 11:53