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() vs Math.round():小数の丸め方を極める!

Posted at

小数を M 桁まで丸めるなら Math.round() より toFixed() のほうが断然スマート。技術メモメモ!


問題: 小数を M桁まで表示

📌 仕様
実数 N を小数第 M 位まで四捨五入
小数部が M 位に満たない場合は 0 で埋める


入力例 → 出力例

入力:  3.14159 3  
出力:  3.142  


NG例: Math.round() で分岐すると…

const [N, M] = input.split(" ");
const num = Number(N);
const decimalPlaces = Number(M);
let result = "";

if (decimalPlaces === 1) {
    result = (Math.round(num * 10) / 10).toString();
} else if (decimalPlaces === 2) {
    result = (Math.round(num * 100) / 100).toString();
}

😱 問題点

✅ M の値ごとに if 文を分岐 → 可読性最悪
✅ 0 埋め処理がない → 表示がズレる可能性


OK例: toFixed(M) で一発解決!

const [N,M] = input.split(" ").map(Number);
console.log(N.toFixed(M));

🎯 toFixed(M) の強み

M 桁まで四捨五入 → Math.round() のような分岐不要
✔ 小数部が足りないときは自動 0 埋め


おまけ: toFixed() なしで解決する方法

const [N, M] = input.split(" ");
const num = Number(N);
const decimalPlaces = Number(M);
let result = "";

let result = (Math.round(num * 10**M) / 10**M).toString();
if (!result.includes(".")) result += ".";
result += "0".repeat(M - (result.split(".")[1] || "").length);
console.log(result);

📌 何してる?

  • Math.round()M 位まで四捨五入
  • 0 埋めを手動処理


結論

🚀 toFixed(M) を使えば 一行で M 桁まで丸められる!
🚀 Math.round() は 0 埋め処理が必要で 冗長になりがち


僕の失敗談と解決話!

0
0
2

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?