Quantcast
Channel: Active questions tagged python - Stack Overflow
Viewing all articles
Browse latest Browse all 23390

Python float to int conversion [duplicate]

$
0
0

Basically, I'm converting a float to an int, but I don't always have the expected value.

Here's the code I'm executing:

x = 2.51

print("--------- 251.0")y = 251.0print(y)print(int(y))print("--------- 2.51 * 100")y = x * 100print(y)print(int(y))print("--------- 2.51 * 1000 / 10")y = x * 1000 / 10print(y)print(int(y))print("--------- 2.51 * 100 * 10 / 10")y = x * 100 * 10 / 10print(y)print(int(y))x = 4.02print("--------- 402.0")y = 402.0print(y)print(int(y))print("--------- 4.02 * 100")y = x * 100print(y)print(int(y))print("--------- 4.02 * 1000 / 10")y = x * 1000 / 10print(y)print(int(y))print("--------- 4.02 * 100 * 10 / 10")y = x * 100 * 10 / 10print(y)print(int(y))

And here's the result (first value is the result of the operation, second value is int() of the same operation):

--------- 251.0251.0251--------- 2.51 * 100251.0250--------- 2.51 * 1000 / 10251.0251--------- 2.51 * 100 * 10 / 10251.0250--------- 402.0402.0402--------- 4.02 * 100402.0401--------- 4.02 * 1000 / 10402.0401--------- 4.02 * 100 * 10 / 10402.0401

2.51 and 4.02 are the only values that lead to that strange behaviour on the 2.50 -> 5.00 range. Every other two digits value in that range converts to int without any problem when given the same operations.

So, what am I missing that leads to those results? I'm using Python 2.7.2 by the way.


Viewing all articles
Browse latest Browse all 23390

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>