Javascript TIPS No.7 数値の整数部分を取り出す「Math.floor() Math.ceil()」

  • 数値から、整数部分だけを取り出すには「Math.floor()」もしくは「Math.ceil()」を利用します。
  • 対象の数値が正数の場合は「Math.floor()」負数の場合は「Math.ceil()」を利用します。
  • 対象の数値は「数値形式」でも「文字列形式」でもOKです(ただし、2バイト文字やアルファベットが含まれている場合はエラーとなります)

文法

Math.floor(検索対象の数値が正数の場合)
Math.ceil(検索対象の数値が負数の場合)

サンプルコード

<html lang="ja-JP">
<title>数値から、整数部分を取り出す</title>
<script type=text/javascript>

function funcFloor(){
n = Math.floor(document.getElementById('idFloorIn').value);
document.getElementById('idFloorOut').value = n;
}

</script>
</head>
<body>

<input type="text" id="idFloorIn" value="1.15489315486241">
<input type="button" onClick="funcFloor()" value="整数を抜き出す">
<br><br><br><br>
<input type="text" id="idFloorOut" value="">

</body>
</html>

サンプルを見る

解説

  • 上記では、Math.floorを利用しています。
処理1
  • input要素(idFloorIn)からvalueを取得し、さらに整数のみを取り出して、変数(n)に格納する)
n = Math.floor(document.getElementById('idFloorIn').value);
処理2
  • 変数(n)をinput要素(idFloorOut)に代入する
document.getElementById('idFloorOut').value = n;


上の方法で、整数だけを取り出すことに成功しました。
floorの部分をceilに変えれば、検索対象の数値が負数でも動作します。
しかし、input要素に入力される数値は負数だけとも正数だけとも限りません。
そこで、両方に対応した物を作ってみました。

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=shift-js" />
<title>数値から、整数部分を取り出す</title>
<script type=text/javascript>

function funcFloor(){
n = document.getElementById('idFloorIn').value;

if(n > 0){n = Math.floor(n)}else{n = Math.ceil(n)};

document.getElementById('idFloorOut').value = n;
}

</script>
</head>
<body>
<input type="text" id="idFloorIn" value="1.15489315486241">
<input type="button" onClick="funcFloor()" value="整数を抜き出す">
<br><br>
↓
<br><br>
<input type="text" id="idFloorOut" value="">
</body>
</html>

サンプルを見る

解説

  • input要素に入力されている数値が正数なら「Math.floor」負数なら「Math.ceil」するようにif分で振り分けてみました。
処理1(要素の値を取得)
  • input要素(idFloorIn)のvalueを変数(n)に格納します。
n = document.getElementById('idFloorIn').value;
処理2(処理の振り分け)
  • 変数(n)の値が0以上なら「Math.floor」それ以外なら「Math.cell」したものを、変数(n)に格納する。
if(n > 0){n = Math.floor(n)}else{n = Math.ceil(n)};
処理3(結果を格納)

input要素(idFloorOut)に変数(n)の値を格納します。

document.getElementById('idFloorOut').value = n;

これで、検索対象の数値が負数でも正数でも整数を抜き出すことが可能です。