JavaScriptの数値の表記を指定するサンプルです。
toFixed、toPrecision、toExponentialメソッドを使用します。
| 確認環境 ・Windows10 ・Google Chrome |
目次
固定小数点で表示(toFixed)
toFixedメソッドは、固定小数点の表記文字列を返します。
<script>
const a = 1;
console.log(a.toFixed(3)); //1.000
console.log(a.toFixed(4)); //1.0000
const b = 123.4567
console.log(b.toFixed(3)); //123.457
console.log(b.toFixed(4)); //123.4567
console.log(b.toFixed(5)); //123.45670
</script>
以下は、MDNのtoFixedのリンクです。
https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed
指定された精度で表示(toPrecision)
toPrecisionメソッドは、指定された精度で表した文字列を返します。
<script>
const a = 1;
console.log(a.toPrecision(3)); //1.00
console.log(a.toPrecision(4)); //1.000
const b = 123.4567
console.log(b.toPrecision(3)); //123
console.log(b.toPrecision(4)); //123.5
console.log(b.toPrecision(5)); //123.46
</script>
以下は、MDNのtoPrecisionのリンクです。
https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Global_Objects/Number/toPrecision
指数表記で表示(toExponential)
toExponentialメソッドは、指数表記で表した文字列を返します。
<script>
const a = 1;
console.log(a.toExponential(3)); //1.000e+0
console.log(a.toExponential(4)); //1.0000e+0
const b = 123.4567
console.log(b.toExponential(3)); //1.235e+2
console.log(b.toExponential(4)); //1.2346e+2
console.log(b.toExponential(5)); //1.23457e+2
</script>
以下は、MDNのtoExponentialのリンクです。
https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Global_Objects/Number/toExponential
関連の記事
JavaScript URIエンコード(encodeURIComponentとdecodeURIComponent)
JavaScript 文字列と数値の変換(parseInt/Number/String/+演算子)