0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

SQLメモ

Last updated at Posted at 2021-02-23

小数点以下のまるめ関数挙動をまとめておく。自分用メモ

まとめている関数

  • round(数値, 桁数)

    数値を指定した桁数で四捨五入して返す(桁数入力の無い場合は、整数になる)
  • trunc(数値, 桁数)

    数値を指定した桁数で切り捨てて返す(桁数入力の無い場合は、整数になる)
  • floor(数値)

    指定した数値の切り捨て整数値を返す
  • ceil(数値)

    指定した数値の切り上げ整数値を返す

実際にやってみる

round(10.5)    # 11.0
round(-10.5)   # -11.0
trunc(10.5)    # 10.0
trunc(-10.5)   # -10.0
floor(10.5)    # 10.0
floor(-10.5)   # -11.0
ceil(10.5)     # 11.0
ceil(-10.5)    # -10.0

桁数はどこまで表示するかを表す。1が小数点第一位、0が整数部分一桁目、−1が整数部分二桁目。
つまり1の場合は、小数点第二位までを端数として操作し、小数点第一位までを表示する。
これを前提にroundとtruncの挙動を比べてみる。

roundの挙動を確認

round(156.753,3)   # 156.753
round(156.753,2)   # 156.75
round(156.753,1)   # 156.8
round(156.753,0)   # 157.0
round(156.753,-1)  # 160.0
round(156.753,-2)  # 200.0
round(156.753,-3)  # 0.0

truncの挙動を確認

trunc(156.753,3)   # 156.752
trunc(156.753,2)   # 156.75
trunc(156.753,1)   # 156.7
trunc(156.753,0)   # 156.0
trunc(156.753,-1)  # 140.0
trunc(156.753,-2)  # 100.0
trunc(156.753,-3)  # 0.0

数直線上の挙動でまとめてみる

  • round(数値, 桁数)

    絶対値の大きい方に動く
  • trunc(数値, 桁数)

    絶対値の小さい方の動く
  • floor(数値)

    数値の小さい方に動く
  • ceil(数値)

    数値の大きい方に動く

ごちゃつくと計算を繰り返しているうちに数値が合わなくなるので注意が必要です。

0
0
0

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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?