javascript 10進数をn進数に変換する
- 2020.09.15
- javascript
- javascript

javascriptで、toStringを使って、10進数をn進数に変換するサンプルコードを記述してます。
環境
- OS windows10 pro 64bit
- Apache 2.4.43
- ブラウザ chrome 84.0.4147.105
toString使い方
toStringを使うと、10進数をn進数に変換することが可能です。
1 |
値.toString(n); |
toString使い方
1 2 3 4 5 6 7 8 9 |
var num = 8; // 2進数 console.log(num.toString(2)); // 1000 // 4進数 console.log(num.toString(4)); // 20 // 8進数 console.log(num.toString(8)); // 10 // 16進数 console.log(num.toString(16)); // 8 |
サンプルコード
以下は、
「計算」ボタンをクリックすると、フォームに入力された数字を、
フォームで指定した基数に変換して表示する
サンプルコードとなります。
※cssには「bootstrap material」を使用してます。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 |
<!DOCTYPE html> <html lang="ja"> <head> <meta charset="utf-8"> <title>mebeeサンプル</title> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700|Material+Icons"> <link rel="stylesheet" href="https://unpkg.com/bootstrap-material-design@4.1.1/dist/css/bootstrap-material-design.min.css" integrity="sha384-wXznGJNEXNG1NFsbm0ugrLFMQPWswR3lds2VeinahP8N0zJw9VWSopbjv2x7WCvX" crossorigin="anonymous"> </head> <style> .main { margin: 0 auto; margin-top: 200px; display: flex; flex-direction: column; align-items: center; font-size: 25px; width: 500px; } </style> <script> function hoge() { // 基数を取得 var radix = document.getElementById('num1').value; // 値を取得 var num = document.getElementById('num2').value; // 変換 var result = Number(num).toString(radix); // 実行結果を表示 var obj = document.getElementById('num'); obj.textContent = result; }</script> <body> <div class="main"> <h2><span id="num" class="badge badge-primary">計算結果</span></h2> <form> <div class="form-group"> <label class="bmd-label-floating">基数</label> <input id="num1" type="number" class="form-control"> </div> <div class="form-group"> <label class="bmd-label-floating">値</label> <input id="num2" type="number" class="form-control"> </div> </form> <button type="button" onclick="hoge()" class="btn btn-raised btn-primary" > 計算 </button> </div> </body> </html> |
変換されていることが確認できます。

-
前の記事
javascript 数値の最小値を取得する 2020.09.14
-
次の記事
Virtual BoxにMX linux19.2をインストールする 2020.09.15
コメントを書く