このエントリーをはてなブックマークに追加


小数点以下の値の操作・四捨五入や切上げ、切捨て

Pythonで四捨五入や小数点以下のの切り捨てや切り上げ方法のサンプルコードを以下に記します。


スポンサーリンク

関連記事

動作確認環境

$ python --version
Python 2.7.3
$ lsb_release -d
Description:    Ubuntu 12.04.4 LTS

int

intにより小数点以下を切り捨て整数化します。

  • サンプルコード
    n = 123.98765
    print "n = " + str(n)
    print "int(n) = " + str(int(n))
  • 実行結果
    n = 123.98765
    int(n) = 123

指定した場所で小数点値を四捨五入

roundを使って小数点の四捨五入を実現することができます。

  • サンプルコード
    n = 123.987654
    print "n = " + str(n)
    print "round(n,0) = " + str(round(n,0))
    print "round(n,1) = " + str(round(n,1))
    print "round(n,2) = " + str(round(n,2))
     print "round(n,3) = " + str(round(n,3))
    print "round(n,4) = " + str(round(n,4))
    print "round(n,5) = " + str(round(n,5))
    print "round(n,6) = " + str(round(n,6))
  • 実行結果
    n = 123.987654
    round(n,0) = 124.0
    round(n,1) = 124.0
    round(n,2) = 123.99
    round(n,3) = 123.988
    round(n,4) = 123.9877
    round(n,5) = 123.98765
    round(n,6) = 123.987654

切り捨て math.floor

mathモジュールのfloorを使って切り捨てを行います。

  • サンプルコード
    import math
    
    n = 123.987654
    print "n = " + str(n)
    print "math.floor(n) = ", math.floor(n)
  • 実行結果
    n = 123.987654
    math.floor(n) =  123.0

切り上げ math.ceil

mathモジュールのceilを使って切り上げを行います。

  • サンプルコード
    n = 123.987654
    math.ceil(n) =  124.0
  • 実行結果
    n = 123.987654
    math.ceil(n) =  124.0

以上、小数点以下の値の操作・四捨五入や切上げ、切捨てのサンプルコードでした。


スポンサーリンク


トップ   編集 凍結 差分 バックアップ 添付 複製 名前変更 リロード   新規 一覧 検索 最終更新   ヘルプ   最終更新のRSS
Last-modified: 2015-03-20 (金) 22:31:31