Search code examples
pythonpython-3.xformatf-string

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


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.


Solution

  • If your string is going to have just floating number, then you can use str.rstrip() (instead of str.strip() which you have right now). Also, you need to make a chained call to it firstly with '0' and then with '.' like .rstrip('0').rstrip('.') to handle the integers with trailing zeros like 10000.

    However, if you can have other characters in your string, and you want to strip 0 just for numbers, then you can use nested f-string as:

    >>> f"{f'{1002/1000:.2f}'.rstrip('0').rstrip('.')} number"
    '1 number'
    
    >>> f"{f'{1009/1000:.2f}'.rstrip('0').rstrip('.')} number"
    '1.01 number'
    
    >>> f"{f'{1000:.2f}'.rstrip('0').rstrip('.')} number"
    '1000 number'