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?

四捨五入をする関数

Last updated at Posted at 2024-01-04

四捨五入関数

以前に何処かに書いて,コメントももらっていたのが行方不明になっていました。

新たに頂いたコメントに基づいて,本文を追加・訂正します。
さらなるコメント,多言語による実装例等歓迎です。

Python

def shishagonyu(x, n=0):
    return (-1 if x < 0 else 1 if x > 0 else 0)*int(abs(x) * 10**n + 0.5) / 10**n
(shishagonyu(5.15, 1), shishagonyu(-5.15, 1), shishagonyu(0.5), shishagonyu(-0.5))
(5.2, -5.2, 1.0, -1.0)
(shishagonyu(5.25, 1), shishagonyu(-5.25, 1), shishagonyu(1.5), shishagonyu(-1.5))
(5.3, -5.3, 2.0, -2.0)

@shiracamus(しらかみゅ)

abs を取らなくてもできる。

def shishagonyu(x, n=0):
    return int(x * 10**n + (-0.5 if x < 0 else 0.5)) / 10**n
(shishagonyu(5.15, 1), shishagonyu(-5.15, 1), shishagonyu(0.5), shishagonyu(-0.5))
(5.2, -5.2, 1.0, -1.0)
(shishagonyu(5.25, 1), shishagonyu(-5.25, 1), shishagonyu(1.5), shishagonyu(-1.5))
(5.3, -5.3, 2.0, -2.0)

Julia

shishagonyu(x, n=0) = sign(x)*Int64(abs(x)*10^n + 0.5)/10^n;
(shishagonyu(5.15, 1), shishagonyu(-5.15, 1), shishagonyu(0.5), shishagonyu(-0.5))
(5.2, -5.2, 1.0, -1.0)
(shishagonyu(5.25, 1), shishagonyu(-5.25, 1), shishagonyu(2.5), shishagonyu(-2.5))
(5.3, -5.3, 3.0, -3.0)

@antimon2(Shunsuke GOTOH)

Julia は標準の関数で四捨五入を実現できるものがある。

shishagonyu(x, n=0) = round(x, RoundNearestTiesAway; digits=n);
(shishagonyu(5.15, 1), shishagonyu(-5.15, 1), shishagonyu(0.5), shishagonyu(-0.5))
(5.2, -5.2, 1.0, -1.0)
(shishagonyu(5.25, 1), shishagonyu(-5.25, 1), shishagonyu(2.5), shishagonyu(-2.5))
(5.3, -5.3, 3.0, -3.0)

R

shishagonyu = function(x, n=0) sign(x)*as.integer(abs(x)*10^n + 0.5)/10^n
cat(shishagonyu(5.15, 1), shishagonyu(-5.15, 1), shishagonyu(0.5), shishagonyu(-0.5))
5.2 -5.2 1 -1
cat(shishagonyu(5.25, 1), shishagonyu(-5.25, 1), shishagonyu(2.5), shishagonyu(-2.5))
5.3 -5.3 3 -3

@shiracamus(しらかみゅ) さんの指摘により修正

shishagonyu = function(x, n=0) as.integer(x * 10^n + ifelse(x < 0, -0.5, 0.5)) / 10^n
cat(shishagonyu(5.15, 1), shishagonyu(-5.15, 1), shishagonyu(0.5), shishagonyu(-0.5))
5.2 -5.2 1 -1
cat(shishagonyu(5.25, 1), shishagonyu(-5.25, 1), shishagonyu(2.5), shishagonyu(-2.5))
5.3 -5.3 3 -3
0
0
2

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?