[python] Rounding to keep N decimal places, truncation to keep decimals

Table of contents

1. Environment

2. Applicable scenarios

3. Specific method code and description

1. Method 1: numpy-around() method, rounding

2. Method 2: String formatting (there are two ways, both of which are rounded) [recommended]

1) %.4f method

2) {:.4f} method

 3. Method 3: format function method [recommended], rounding

 4. Method 4: round() method, rounding

 5. Method 5: The math-floor() function performs truncation instead of rounding


1. Environment

windows + jupyter notebook

2. Applicable scenarios

When I was looking for Moran’s index (floating-point number) in data visualization, the original data had many digits after the decimal point (0.4256749604873086), and four digits after the decimal point needed to be reserved, so this article uses the four digits after the floating-point number as an example to list .

3. Specific method code and description

1. Method 1: numpy-around() method, rounding

import numpy as np
test = 0.4256749604873086
print("原数据:", test)

#numpy around 方法
afterTrans = np.around(test, 4)
print("保留小数点后四位(四舍五入):", afterTrans)

 

2. Method 2: String formatting (there are two ways, both of which are rounded) [recommended]

1) %.4f method

2) {:.4f} method

test = 0.4256749604873086
print("原数据:", test)

#字符串格式化方法  法一
print("%.4f" % test)

#字符串格式化方法  法二
print("{:.4f}".format(test))

 

 3. Method 3: format function method [recommended], rounding

test = 0.4256749604873086
print("原数据:", test)
print(format(test, '.4f'))

 4. Method 4: round() method, rounding

test = 0.4256749604873086
print("原数据:", test)
print(round(test, 4))

 5. Method 5: The math-floor() function performs truncation instead of rounding

import math
test = 0.4256749604873086
print("原数据:", test)
truncated_num = math.floor(test * 10000) / 10000
print(truncated_num)

 

--END--

Guess you like

Origin blog.csdn.net/qq_41539778/article/details/131288899