Dania
Dania

Reputation: 1017

Get a decimal point result upto n number of precision in python

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

Upvotes: 0

Views: 234

Answers (2)

user4815162342
user4815162342

Reputation: 154886

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

Upvotes: 5

RyanU
RyanU

Reputation: 130

If you're using Python 3.x, you should try this :

print(str(float(29631)/1073741824))

Upvotes: -1

Related Questions