crankshaft
crankshaft

Reputation: 2677

Python 2.7 rounding vs Python 3

Second question regarding python2 vs python3 today, as I am having to revert back to v2 with a script I wrote for V3 and it's not working:

print(str(27062/1000))

Using python3 this returns 27.062, but under python2 it returns 27.

27.062 is the value I require, how can I do this under python2 ??

Thanks

Upvotes: 0

Views: 75

Answers (2)

Lev Levitsky
Lev Levitsky

Reputation: 65791

Convert to a float:

In [1]: 27062.0/1000
Out[1]: 27.062

In [2]: float(27062)/1000
Out[2]: 27.062

Or you can do:

In [3]: from __future__ import division

and have the Python3-like behavior in Python2:

In [4]: 27062/1000
Out[4]: 27.062

In that case you can get integer division by using the // operator:

In [5]: 27062//1000
Out[5]: 27

Upvotes: 1

rlms
rlms

Reputation: 11060

Short answer - convert to float. print(str(float(27062)/1000))

In Python 2.x, / is the floor division operator for integers - it returns how many times one number will go into another. In Python 3.x, the floor division operator has been changed to //, and / behaves like "normal" division.

Upvotes: 0

Related Questions