Python中四舍五入保留小数位数的解决方案(包括数组)

import math
def cei(n,d=2):
    d = int('1' + ('0' * (d+1)))
    x = int((n*d-5 if n<0 else n*d+5)/10)/(d/10) 
    return x

cei(-12.200356,4)

-12.2004

这是再加一个将数组内数字全部四舍五入保留小数位数的解决方案

def cei(M,d=2):
    
    np.set_printoptions(suppress=True)
    d = int('1' + ('0' * d))
    n = np.array(M)
    shap = n.shape
    n = n.reshape(-1)
#     X=[]
    for i, v in enumerate(n):
        if v>=0:
            x = int(v*d+.5)/d
        else:
            x = int(v*d-.5)/d
        if i == 0:
            X = np.array(x)
        else:
            X = np.append(X, np.array(x))
    return X.reshape(shap)

x = [[34.4558, -2.222],[1213.33333,-0.5678]]
cei(x) 

array([[ 34.46, -2.22],
[1213.33, -0.57]])

如上

你可能感兴趣的:(Python,算法)