Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to look if first 2 numbers after the decimal point match the condition

I’m trying to make a simple if elif else statement that does different things based on the number.

number = 25

if '.25' in str (number):
    number1 = number - 0.25, number + 0.25
    print(number1)

elif '.75' in str (number):
    number1 = number - 0.25, number + 0.25
    print(number1)

elif number == 0:
    numberformated = format(number, '.1f')
    print(numberformated)

else:
    print(number)

My problem is when number is something like 1.754 then

elif '.75' in str (number): 

gets chosen, but I only want when the number only contains .75 after the decimal point for that elif to run.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

So if number is 17.753 I want the code inside

else 

to be executed and not the

elif '.75' in str (number):

How could I achive this?

>Solution :

You can compare ‘.75’ with last 3 symbols in the string of your number:

elif '.75' == str(number)[-3:]:

But I believe there is a more convenient and beautiful way.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading