javascript 数値を指数表記にして文字列で返す

javascript 数値を指数表記にして文字列で返す

javascriptで、toExponentialを使用して、数値を指数表記にして文字列で返すサンプルコードを記述してます。

環境

  • OS windows10 pro 64bit
  • Apache 2.4.43
  • ブラウザ chrome 103.0.5060.114

toExponential使い方

「toExponential」を使用すると、数値を指数表記にして文字列にすることが可能です。

数値.toExponential()

数値.toExponential(少数以下の桁数も指定できる)

実際に使用してみます。

let num = 100.1234567;

console.log(num.toExponential()); // 1.001234567e+2
console.log(num.toExponential(2)); // 1.00e+2
console.log(num.toExponential(3)); // 1.001e+2
console.log(num.toExponential(4)); // 1.0012e+2
console.log(num.toExponential(5)); // 1.00123e+2

「toExponential」に指定できる範囲は「0~100」で、超えるとエラーとなります。

let num = 100.1234567;

console.log(num.toExponential(-1)) // Uncaught RangeError: toExponential() argument must be between 0 and 100

少数は使用可能で、切り捨てされるようです。

let num = 100.1234567;

console.log(num.toExponential(2.1)) // 1.00e+2
console.log(num.toExponential(2.9)) // 1.00e+2
console.log(num.toExponential(2.9999)) // 1.00e+2

数値の文字列も、使用することができます。

let num = 100.1234567;

console.log(num.toExponential('2')) // 1.00e+2
console.log(num.toExponential('02')) // 1.00e+2
console.log(num.toExponential('2.1')) // 1.00e+2

サンプルコード

以下は、
「変換」ボタンをクリックすると、フォームに入力した値を指数表記にして表示する
サンプルコードとなります。

※cssには「bootstrap5」を使用してます。「bootstrap5」は、IEのサポートを終了してます。

<!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://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css">
</head>
<style>
  .main {
    margin: 0 auto;
    margin-top: 200px;
    display: flex;
    flex-direction: column;
    align-items: center;
    font-size: 30px;
  }
</style>
<script>
  function hoge() {
    
    // フォームの値を取得
    let num = document.getElementById('foo').value;

    // 表示用の要素を取得
    let elm = document.getElementsByClassName("badge")[0];
    // 指数変換
    elm.textContent = Number(num).toExponential();

  }

  window.onload = function () {

    // ボタンを取得
    let elmbtn = document.getElementById('btn');
    // クリックイベントを登録
    elmbtn.onclick = function () {
      hoge();
    };

  }
</script>

<body>
  <div class="main container">
    <h2><span class="badge bg-primary">指数変換</span></h2>

    <div class="row">
      <div class="input-group mb-3">
        <input id="foo" type="number" class="form-control">
      </div>
    </div>
    <div class="row">
      <button id="btn" type="button" class="btn btn-warning">
        変換
      </button>
    </div>

  </div>
</body>

</html>

指数表記に変換されていることが確認できます。

また、javascript部はdocument.getElementByIdを省略して記述することも可能です。関数もアロー関数を使用できます。

const hoge = () =>{

  // 表示用の要素を取得
  let elm = document.getElementsByClassName("badge")[0];
  // 指数変換
  elm.textContent = Number(foo.value).toExponential();

}

window.onload = () => {
  // クリックイベントを登録
  btn.onclick = () => {
    hoge();
  };
}