Rounding scientific notation in python

If you want to use Python's f-string syntax introduced in Python 3.6, specify the format after the variable, separated by :, e.g.:

>>> res = 2.32432432423e25
>>> f'The result is {res:.3e}'
'The result is 2.324e+25'

You'll need to use string formatting for this:

'{:0.3e}'.format(2.32432432423e25)

The reason is that round is for specifying the number of the digits after the ones place, which is not really relevant when your numbers are O(25).


I was looking for an answer to this and mostly found string answers. While that is typically the best way to handle this question (because floats are always rounded to their defined precision regardless), there are situations where you'd like to round a float to a given decimal precision (plus whatever float imprecision added on) and I couldn't find a good answer. Here's what I came up with, I believe it handles all the possible cases: input of zero, input < 1, input > 1 for both positive and negative numbers:

def precision_round(number, digits=3):
    power = "{:e}".format(number).split('e')[1]
    return round(number, -(int(power) - digits))

Tags:

Python