[Python] How to skip trailing zeroes from a decimal with f-strings

Discussão em 'Python' iniciado por Stack, Junho 16, 2025.

  1. Stack

    Stack Membro Participativo

    I want to set a precision in my f-strings, but I do not want the the trailing zeroes in the decimal part.

    i = 1002
    print(f'{i/1000:.2f}') # 1.00 but this must be 1

    i = 1009
    print(f'{i/1000:.2f}') # 1.01, this is correct


    The first print must be 1, my expected behavior is seen in the second print where it is 1.01.

    I tried :g but it works for the first print but fails for the second.

    i = 1000
    print(f'{i/1000:.2g}') # 1, this is correct but
    i = 1009
    print(f'{i/1000:.2g}') # 1, but this must be 1.01


    One way I tried is f'{i/1000:.2f}'.strip('.0') but I wanted to know if there is a better way.

    Edit :

    In my actual code if i is 100000 then the denominator will also be 100000 (smallest digit in the order of i) in other words the denominator in my code will always be such that the i//denominator will always yield a single digit.

    Continue reading...

Compartilhe esta Página