Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
4 views
in Python by (47.6k points)

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.0 

print(y) 

print(int(y)) 

print("--------- 2.51 * 100") 

y = x * 100 

print(y) 

print(int(y)) 

print("--------- 2.51 * 1000 / 10") 

y = x * 1000 / 10 

print(y) 

print(int(y)) 

print("--------- 2.51 * 100 * 10 / 10") 

y = x * 100 * 10 / 10 

print(y) 

print(int(y)) 

x = 4.02 

print("--------- 402.0") 

y = 402.0 

print(y) 

print(int(y)) 

print("--------- 4.02 * 100") 

y = x * 100 

print(y) 

print(int(y)) 

print("--------- 4.02 * 1000 / 10") 

y = x * 1000 / 10 

print(y) 

print(int(y)) 

print("--------- 4.02 * 100 * 10 / 10") 

y = x * 100 * 10 / 10 

print(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.0 

251.0 

251 

--------- 2.51 * 100 

251.0 

250 

--------- 2.51 * 1000 / 10 

251.0 

251 

--------- 2.51 * 100 * 10 / 10 

251.0 

250 

--------- 402.0 

402.0 

402 

--------- 4.02 * 100 

402.0 

401 

--------- 4.02 * 1000 / 10 

402.0 

401 

--------- 4.02 * 100 * 10 / 10 

402.0 

401

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.

1 Answer

0 votes
by (106k points)

To do Python float to int conversion you can use the below-mentioned code:-

The int() function simply truncates the number at the decimal point, giving 250. Use

int(round(2.51*100))

To know more about this you can have a look at the following video tutorial:-

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Dec 3, 2020 in Python by laddulakshana (16.4k points)

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...