Reputation: 2584
I have a number like 2.32432432423e25
in python that is the result of a computation.
I want to round this to 3 decimal points to get the output:
2.324e25
I have tried to use:
x = 2.32432432423e25
number_rounded = round(x, 3)
But when I print number_rounded
it outputs a number with the same format as x
.
How do I limit the display of x
to just 4 significant digits?
Upvotes: 33
Views: 35904
Reputation: 317
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.
def precision_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 array
for dim0 in range(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 in zip(numbers[dim0, :], powers)]
# returning the original shape of the `numbers`
if out_array.shape[0] == 1 and 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
Upvotes: 0
Reputation: 51
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))
Upvotes: 4
Reputation: 7844
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'
Upvotes: 13
Reputation: 68186
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).
Upvotes: 40