Search code examples
pythondecimalmatchingdigits

Need matching digits between two decimals


let's say I have 2 decimals(float).

a = 123.62903
b = 123.6233

now I want the result to matching digits of this decimal. so result here should be

123.62.

If,

a =234.2387
b =232.2138

then, the result should be

result = 23.

It would be a great help thank you.


Solution

  • Using zip and a simple iteration.

    Demo:

    a = 123.62903
    b = 123.62333
    
    res = ''
    for i, v in zip(str(a), str(b)):
        if i != v:
            break
        else:
           res += v
    
    if res:
        print(float(res) if "." in res else int(res))
    

    Output:

    123.62