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

Time:01-27

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.

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?

CodePudding user response:

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.

  • Related