JavaScript おれおれ Advent Calendar 2011 – 7日目
Math
オブジェクトに小数点付きの数値を整数にするメソッドが幾つかあるので、parseInt()
と併せてまとめてみます。
Math.ceil()
Math.floor()
Math.round()
parseInt()
Math.ceil()
与えられた値を下回らない最小の整数、つまり同じか大きい整数を返します。
console.log(Math.ceil(3.5)); // => 4 console.log(Math.ceil(-3.5)); // => -3
Math.floor()
与えられた値を上回らない最大の整数、つまり同じか小さい整数を返します。
console.log(Math.floor(3.5)); // => 3 console.log(Math.floor(-3.5)); // => -4
Math.round()
いわゆる四捨五入を行います。
負数の場合の結果は想定外かもしれません。「0.5
未満を切り捨てる(0
に近づける)」のではなく、「0.5
より小さければ小さい整数にする(負の∞に近づける)」という、正負に依らない規則になっています。
console.log(Math.round(3.5)); // => 4 console.log(Math.round(3.49)); // => 3 console.log(Math.round(-3.5)); // => -3 console.log(Math.round(-3.51)); // => -4
parseInt()
小数点以下をごっそり切り捨てます。
console.log(parseInt(3.5)); // => 3 console.log(parseInt(-3.5)); // => -3
基数変換の機能があります。