简体   繁体   English

在python中舍入科学记数法

[英]Rounding scientific notation in python

I have a number like 2.32432432423e25 in python that is the result of a computation.我在 python 中有一个像2.32432432423e25这样的2.32432432423e25 ,它是计算的结果。

I want to round this to 3 decimal points to get the output:我想将其四舍五入到 3 个小数点以获得输出:

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 .但是当我打印number_rounded它会输出一个与x格式相同的数字。

How do I limit the display of x to just 4 significant digits?如何将x的显示限制为 4 位有效数字?

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).原因是round用于指定个位后的位数,当您的数字为O (25) 时,这与实际无关。

If you want to use Python's f-string syntax introduced in Python 3.6, specify the format after the variable, separated by : , eg:如果要使用 Python 3.6 中引入的 Python 的 f-string 语法,请在变量后指定格式,用:分隔,例如:

>>> res = 2.32432432423e25
>>> f'The result is {res:.3e}'
'The result is 2.324e+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:这是我想出的,我相信它可以处理所有可能的情况:输入零,输入 < 1,输入 > 1 对于正数和负数:

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

Building on top of @Josh Duran nice function/idea, here is the same func that can handle up-to 2-D arrays.建立在@Josh Duran 不错的函数/想法之上,这里是可以处理最多二维数组的相同函数。 Maybe someone can modify this for the ndarrays.也许有人可以为 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 & 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM