javascript BigIntをNumberに変換する
- 作成日 2022.04.21
- 更新日 2022.11.21
- javascript
- javascript
javascriptで、BigIntをNumberに変換するサンプルコードを記述してます。「Number」を使用することで変換することができます。逆に「BigInt」に変換するには「BigInt」を使用します。
環境
- OS windows11 home
- Apache 2.4.43
- ブラウザ chrome 107.0.5304.107
変換方法
BigIntをNumberに変換するには、「Number」を使用します。
let num = 10n
console.log( typeof( num ) ) // bigint
console.log( typeof( Number(num) ) ) // number
変換されていることが確認できます。
変換することで、Bigintと通常の数値で演算することが可能になります。
console.log( Number(num) + 10 ) // 20
「parseInt」を使用して変換することも可能です。
let num = 10n
console.log( typeof( num ) ) // bigint
console.log( typeof( parseInt(num) ) ) // number
console.log( parseInt(num)+ 10 ) // 20
パフォーマンスは「Number」の方がいいです。
実行回数:1000000回 関数名:parseInt 実行時間:78.7(ms)
実行回数:1000000回 関数名:Number 実行時間:16.5(ms)
BigInt型に変更
逆に、NumberをBigIntに変更する場合は「BigInt」を使用します。
let num = 10
console.log( typeof( num ) ) // number
console.log( typeof( BigInt(num) ) ) // bigint
BigIntに変換することで、BigInt同士の演算が可能になります。
console.log( BigInt(num) + 10n ) // 20n
-
前の記事
jquery キーが押されたイベントを取得する 2022.04.20
-
次の記事
jquery マウスクリックが離されたイベントを取得する 2022.04.21
コメントを書く