pythonroundingnumber-formatting

Format number to at most n digits in python


I know I can use format in order to format a number to whatever format. What I want is to format to at most n digts.

This can be achieved using the g-format-specifier. But there's one caveat here. What if my input is a really small number, e.g. -0.0000000001. With g this prints as -1e-10, but I want it to return simply 0.

I tried to do format(round(mynumber, 7)), but that interestingly gave me -0 (with a leading -) when mynumber is negative near zero.

How can I format mynumber to at most 7 digits without a leading sign, if the number is near zero?

Afterall this is my input and the expected result:

-0.0000000001 -> 0
 0.0000000001 -> 0
 3            -> 3
 3.1415927    -> 3.1415927

Solution

  • or 0 is a short and quick way to replace negative zero:

    for mynumber in -0.0000000001, 0.0000000001, 3, 3.1415927:
        print(round(mynumber, 7) or 0)
    

    Attempt This Online!

    Alternatively, also changing for example 3.0 to 3:

    for mynumber in -0.0000000001, 0.0000000001, 3, 3.1415927, 3.0:
        x = round(mynumber, 7)
        if x.is_integer():
            x = int(x)
        print(x)
    

    Attempt This Online!