LoginSignup
4
5

More than 3 years have passed since last update.

Python リスト 数値を任意の桁数で丸め込む

Last updated at Posted at 2019-10-19

背景

リストを出力した際に、桁数が大きかったので、
簡易的に任意の小数の桁で四捨五入をさせるプログラムはないのかと漁ったが、、、。

そこで情報共有として書き込みさせていただきます。

リスト内の値を小数第n位で丸め込む

コードとしてはシンプルで、
リスト内の値を初期化するように書き換えます。

参考コード

list_内のn番目を丸め込み小数第2位までに変更する

#適当なリストを作成
list_ = [0.987654321, 0.87654321, 0.7654321]

#丸め込みは round を使用
new_list_ = [round(list_[n], 2) for n in range(len(list_ ))] 
#[0.99, 0.88, 0.77]

参考文献

Pythonで小数・整数を四捨五入するroundとDecimal.quantize
Python: リスト要素の桁揃えなどのフォーマット方法

4
5
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
5