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?

toFixed(3) で小数フォーマットを爆速攻略!

Posted at

「小数第3位まで表示&不足分は0埋め」って意外と面倒じゃない?
でも toFixed(3) を知ったら、一瞬で解決したからシェアする!


問題概要

入力: 実数 N
出力: N を小数第3位まで四捨五入し、不足分は0埋め


入力例

3.14159

出力例

3.142


NG例(僕がやらかしたコード)

console.log(Number(input).toPrecision(3)); // ❌ "3.14"(小数第3位が消えた…)

ミスの原因
toPrecision(3) は「有効桁数3桁」なので、小数の扱いがズレる
✅ 3.14159 は 3.14 になって、小数第3位が表示されないことがある


OK例(正しいコード)

console.log(Number(input).toFixed(3)); // ✅ "3.142"

解説
toFixed(3) なら 小数第3位まで表示&不足分は0埋め
✅ 自動で四捨五入(3.14159 → 3.142)
✅ 文字列として返るので、計算に使うなら parseFloat() で数値化


結論

✔ 小数点以下3桁が欲しいなら toFixed(3) 一択!
toPrecision(n) は「有効桁数指定」なので用途が違う
✔ 「小数フォーマット問題」= toFixed(n) を思い出せ!


僕の失敗談と解決話!

0
0
1

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?