JavaScript | 数値を指定の基数の形式で文字列に変換(toString() メソッド)

javascrpit JavaScript
スポンサーリンク

それでは、toString() メソッドを実際に使って「数値をいろいろな進数で表示する実践例」を紹介します。
初心者でも分かりやすいように、段階的に説明します。

例1:基本的な使い方

const num = 255;

console.log(num.toString());   // "255"(10進数)
console.log(num.toString(2));  // "11111111"(2進数)
console.log(num.toString(8));  // "377"(8進数)
console.log(num.toString(16)); // "ff"(16進数)
JavaScript

🔍 解説:

  • num.toString(基数) で、任意の基数に変換できます。
  • 16進数は、色コード(例:#ff0000)やバイナリデータ表示などでよく使われます。

例2:数値入力して変換(ミニ電卓風)

<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>進数変換ツール</title>
<style>
  body { font-family: sans-serif; text-align: center; margin-top: 50px; }
  input, select { font-size: 1.2em; padding: 0.3em; margin: 0.5em; }
</style>
</head>
<body>
  <h2>🔢 進数変換ツール</h2>
  <p>
    数値:<input id="num" type="number" value="255">
    <br>
    基数:<select id="radix">
      <option value="2">2進数</option>
      <option value="8">8進数</option>
      <option value="10" selected>10進数</option>
      <option value="16">16進数</option>
    </select>
  </p>
  <button onclick="convert()">変換!</button>
  <h3 id="result"></h3>

  <script>
    function convert() {
      const num = Number(document.getElementById("num").value);
      const radix = Number(document.getElementById("radix").value);
      const result = num.toString(radix);
      document.getElementById("result").textContent = `${radix}進数表記:${result}`;
    }
  </script>
</body>
</html>
HTML

🖱 このツールでは、

  1. 数値を入力
  2. 変換したい「基数(2, 8, 10, 16)」を選択
  3. 「変換!」をクリック
    → その進数表記が表示されます。

例3:16進数⇄10進数の相互変換(応用)

// 16進文字列 → 10進数
console.log(parseInt("ff", 16)); // 255

// 10進数 → 16進文字列
console.log((255).toString(16)); // "ff"
JavaScript

🧠 ポイント

  • parseInt("文字列", 基数) は「文字列 → 数値」
  • .toString(基数) は「数値 → 文字列」
  • この2つを組み合わせると、どんな基数の変換も可能になります!

例4:RGBカラーコードを自動生成(実践的な活用)

function randomColor() {
  const r = Math.floor(Math.random() * 256).toString(16).padStart(2, "0");
  const g = Math.floor(Math.random() * 256).toString(16).padStart(2, "0");
  const b = Math.floor(Math.random() * 256).toString(16).padStart(2, "0");
  return `#${r}${g}${b}`;
}

console.log(randomColor()); // 例: "#a3e45b"
JavaScript

toString(16) を使って、RGB値を16進文字列に変換しています。
この方法で、ランダムカラーやCSSカラー生成が簡単にできます。

まとめ

処理メソッド
数値 → 指定進数の文字列toString(基数)(255).toString(16)"ff"
文字列(指定進数) → 10進数parseInt(文字列, 基数)parseInt("ff", 16)255
タイトルとURLをコピーしました