0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

JavaScriptで超巨大数を扱う! Number()で桁落ち? BigInt()も罠?

Last updated at Posted at 2025-04-18

Paizaの問題、見た目シンプルだけど地味に落としがあった!。
出力するだけのはずが、Number() で数が削れちゃった…。↓


🔍 問題概要 (「とても大きな数値を出力」)

入力例: 12345678901234567890
出力例: 12345678901234567890



⚠️ NGコード(桁落ちの原因)

const rl = require('readline').createInterface({ input: process.stdin });

rl.on('line', (input) => {
  const n = Number(input);
  console.log(n);
});

出力結果:

12345678901234567000 // ←あれ?

JavaScriptのNumber型(IEEE 754 double)は約16桁までしか正確に扱えない。


✅ 正しいコード:文字列で扱う

rl.on('line', (input) => {
  console.log(input);
});

文字列のまま出力すれば、精度は失われない。今回は「そのまま出す」だけなので、一切変換しないのが正解!


❌ BigIntも要注意

const big = BigInt(input);
console.log(big); // 出力: 12345678901234567890n ←不正解!

BigIntは便利だけど、出力時に n がつくので、表示するときは文字列化する必要がある!

const big = BigInt(input);
console.log(String(big)); // 出力: 12345678901234567890 ←正解!


✅ 要点まとめ

  • Number()は桁落ちする。特に15桁超えは注意。
  • 出力だけなら、文字列のまま扱うのがベスト。
  • BigIntは演算向き。出力用途には向かない(nがつくため)。

【注意点】
BigInt は 少数(小数点)を扱えない。
Number 型と直接混ぜて使えない。BigInt 同士でしか演算できない。



僕の失敗談(´;ω;`)と解決話!🚀

0
0
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?