Rounding Scientific Notation In Python
Solution 1:
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).
Solution 2:
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'
Solution 3:
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:
defprecision_round(number, digits=3):
power = "{:e}".format(number).split('e')[1]
returnround(number, -(int(power) - digits))
Solution 4:
Building on top of @Josh Duran nice function/idea, here is the same func that can handle up-to 2-D arrays. Maybe someone can modify this for the ndarrays.
defprecision_round(numbers, digits = 3):
'''
Parameters:
-----------
numbers : scalar, 1D , or 2D array(-like)
digits: number of digits after decimal point
Returns:
--------
out : same shape as numbers
'''import numpy as np
numbers = np.asarray(np.atleast_2d(numbers))
out_array = np.zeros(numbers.shape) # the returning arrayfor dim0 inrange(numbers.shape[0]):
powers = [int(F"{number:e}".split('e')[1]) for number in numbers[dim0, :]]
out_array[dim0, :] = [round(number, -(int(power) - digits))
for number, power inzip(numbers[dim0, :], powers)]
# returning the original shape of the `numbers` if out_array.shape[0] == 1and out_array.shape[1] == 1:
out_array = out_array[0, 0]
elif out_array.shape[0] == 1:
out_array = out_array[0, :]
return out_array
Post a Comment for "Rounding Scientific Notation In Python"