[Python]数値の1の位を切り上げるには?

python

どうも、ちょげ(@chogetarou)です。

数値の1の位を切り上げる方法を紹介します。

スポンサーリンク

方法

インターフェース, インターネット, プログラム, ブラウザ, Www

数値の1の位を切り上げる方法は、2つあります。

math.ceil()

1つは、math.ceil()を使う方法です。

まず、mathをインポートします。

import math

次に、mathからceil()を呼び出します。

math.ceil()の引数に、数値を10で割った値を指定します。

そして、math.ceil()の戻り値を10倍します。

result = math.ceil(num / 10) * 10

上記の掛け算は、数値の1の位を切り上げた値を取得します。

使用例

import math

num = 1272
num2 = 3857
num3 = 141

result = math.ceil(num / 10) * 10
result2 = math.ceil(num2 / 10) * 10
result3 = math.ceil(num3 / 10) * 10

print(result)
print(result2)
print(result3)
出力:
1280
3860
150

numpy.ceil()

もう1つは、numpy.ceil()を使う方法です。

まず、numpyをインポートします。

import numpy

次に、numpyからceil()を呼び出します。

ceil()の引数に、数値を10で割った値を指定します。

そして、ceil.floor()の戻り値を10倍します。

result = numpy.ceil(number / 10) * 10

上記の掛け算は、数値の1の位を切り上げた値を取得します。

使用例

import numpy

num = 1272
num2 = 3857
num3 = 141

result = numpy.ceil(num / 10) * 10
result2 = numpy.ceil(num2 / 10) * 10
result3 = numpy.ceil(num3 / 10) * 10

print(result)
print(result2)
print(result3)
出力:
1280.0
3860.0
150.0

まとめ

数値の1の位を切り上げる方法は、次の2つです。

  • math.ceil()を使う方法
    result = math.ceil(num / 10) * 10
  • numpy.ceil()を使う方法
    result = numpy.ceil(number / 10) * 10

コメント

タイトルとURLをコピーしました