Search code examples
pythonrounding

Round to significant figures in python


I want to round like this 42949672 -> 42949700, 2147483647 -> 2147480000, 4252017622 -> 4252020000 etc.

I tried to use following , but only works for the first one. How can I make a more general one? thanks

round(42949672, -2)

Solution

  • I assume you want to round to 6 significant figures. If you want to round ints, you can use

    def round_sf(number, significant):
        return round(number, significant - len(str(number)))
    
    print(round_sf(4252017622, 6))
    

    Result:

    4252020000