[Python] 小数点以下 N 桁を維持するための丸め、小数点以下を維持するための切り捨て

目次

1. 環境

2. 適用可能なシナリオ

3. 具体的なメソッドコードと説明

1. 方法 1: numpy-around() メソッド、丸め

2. 方法 2: 文字列の書式設定 (2 つの方法があり、どちらも丸められます) [推奨]

1) %.4f メソッド

2) {:.4f} メソッド

 3. 方法 3: フォーマット関数による方法 [推奨]、四捨五入

 4. メソッド 4:round() メソッド、丸め

 5. 方法 5: math-floor() 関数は、丸めの代わりに切り捨てを実行します。


1. 環境

Windows + ジュピターノートブック

2. 適用可能なシナリオ

データ視覚化で Moran のインデックス (浮動小数点数) を探していたとき、元のデータには小数点以下の桁数 (0.4256749604873086) が多く、小数点以下 4 桁を予約する必要があるため、この記事では 4 桁を使用します。listの例として浮動小数点数の後に

3. 具体的なメソッドコードと説明

1. 方法 1: numpy-around() メソッド、丸め

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

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

 

2. 方法 2: 文字列の書式設定 (2 つの方法があり、どちらも丸められます) [推奨]

1) %.4f メソッド

2) {:.4f} メソッド

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

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

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

 

 3. 方法 3: フォーマット関数による方法 [推奨]、四捨五入

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

 4. メソッド 4:round() メソッド、丸め

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

 5. 方法 5: math-floor() 関数は、丸めの代わりに切り捨てを実行します。

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

 

- 終わり -

おすすめ

転載: blog.csdn.net/qq_41539778/article/details/131288899