0

I am new to Python. I have two simple questions. In my code, I need to do something like the following:

50-49.9==0.1

but python is giving False. How can I correct this? Also, a similar wrong result I am getting is in the following:

int(10*(1-0.9))

I want the answer to be 1 but I am getting 0.

5
  • Maybe reading through this documentation will be helpful docs.python.org/3/library/functions.html#int Commented Aug 6, 2020 at 5:21
  • What did you expect from the first equation? The second must be due to rounding errors. Commented Aug 6, 2020 at 5:21
  • all floating point truncates towards zero. So (1-0.9) results in 0 so int(10*0) will result in 0 Commented Aug 6, 2020 at 5:22
  • In this case you are checking if 50-49.9 == 0.1. The result is not always 0.1 unless you give round(x,1) so it rounds to 1 decimal place Commented Aug 6, 2020 at 5:25
  • OK, thank you. @JoeFerndz your comment was helpful. Commented Aug 6, 2020 at 5:38

1 Answer 1

0

In summary, the answer to your questions.

  1. 50 - 49.9 == 0.1 will not equate to True as the left hand side is not rounded to one decimal place.

  2. int(10*(1-0.9)) will result in int(10*0) as the equation inside an int statement always truncates towards zero. More details are in https://docs.python.org/3/library/functions.html#int

Sign up to request clarification or add additional context in comments.

2 Comments

Number 2 is not quite correct. The problem is that 1-0.9 evaluates to 0.09999999999999998. Multiply by 10, and the value is below 1. Converting to int will remove the fraction, giving 0
... if you multiply with 100, instead of 10, it will give 9, not 0.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.