数値を丸める
偶数丸め
最近接丸め
JIS丸め
銀行家の丸め
銀行丸め
Ruby
切り捨て
code:rb
3.1415.floor # 3
3.1415.floor(2) # 3.14
四捨五入
code:rb
3.1415.round # 3
3.1415.round(2) # 3.14
3.1415.round(3) # 3.142
切り上げ
code:rb
3.1415.ceil # 4
3.1415.ceil(2) # 3.15
Python
偶数への丸め
code:py
round(1.5) # 2
round(2.5) # 2
round(3.5) # 4
四捨五入
decimalモジュールを使う
code:py
from decimal import Decimal, ROUND_HALF_UP
Decimal("1.5").quantize(Decimal("1"), ROUND_HALF_UP) # Decimal("2")
Decimal("2.5").quantize(Decimal("1"), ROUND_HALF_UP) # Decimal("3")
Decimal("3.5").quantize(Decimal("1"), ROUND_HALF_UP) # Decimal("4")
Decimal("3.14152").quantize(Decimal("0.01"), ROUND_HALF_UP) # Decimal("3.14")
切り捨て
code:py
import math
math.floor(3.14)
JavaScript
四捨五入
結果が整数の場合
code:js
Math.round(1.5) // 2
Math.round(2.5) // 3
小数点第n+1位を四捨五入して、小数点第n位まで求める
$ 10n倍の整数にしてから四捨五入して$ 10nで割る
code:js
const x = 3.1415
Math.round(x * 100) / 100 // 3.14
Math.round(x * 1000) / 1000 // 3.142