LoginSignup
1
0

More than 3 years have passed since last update.

Pythonで数字を四捨五入して丸める関数

Last updated at Posted at 2019-06-19

Pythonで数字を四捨五入して丸める関数

  • 整数に丸める際などに使う関数
  • デフォルトでは整数に丸めてintで出力
  • roundが偶数への丸めだったりで微妙に感じたので
  • 非対称の四捨五入
def pro_round(num, ndigits=0):
    """
    数字を四捨五入で丸める。

    Args:
        num: int or float
            丸めたい数字。

        ndigits: int, optional(default=0)
            丸めた後の小数部分の桁数。0の時は丸めた後intにする。

    Returns:
        rounded: int or float
            丸めた後の数字。
    """
    num *= 10 ** ndigits
    rounded = ( 2* num + 1 ) // 2
    rounded /= 10 ** ndigits

    if ndigits == 0:
        rounded = int(rounded)

    return rounded
1
0
5

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