I\'ve tried searching this and can\'t find a satisfactory answer.
I want to take a list/array of numbers and round them all to n significant figures. I have written
For (display-) formatting in exponential notation, numpy.format_float_scientific(x, precision = n)
(where x is the number to be formatted) seems to work well. The method returns a string
. (This is similar to @Autumn's answer)
Here is an example:
>>> x = 7.92398e+05
>>> print(numpy.format_float_scientific(x, precision = 3))
7.924e+05
Here, the argument precision = n fixes the number of decimals in the mantissa (by rounding off). It is possible to re-convert back this to float
type...and that would obviously keep only the digits present in the string. It would be converted to a positional float format though... more work would be required - so I guess the re-conversion is probably quite a bad idea for large set of numbers.
Also, this doesn't work with iterables...look the docs up for more info.