Pythonで四捨五入や小数点以下のの切り捨てや切り上げ方法のサンプルコードを以下に記します。
htmlinsert(): The given local file does not exist or is not readable.
$ python --version Python 2.7.3
$ lsb_release -d Description: Ubuntu 12.04.4 LTS
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を使って切り捨てを行います。
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を使って切り上げを行います。
n = 123.987654 math.ceil(n) = 124.0
n = 123.987654 math.ceil(n) = 124.0
以上、小数点以下の値の操作・四捨五入や切上げ、切捨てのサンプルコードでした。
htmlinsert(): The given local file does not exist or is not readable.