JavaScriptで数値の四捨五入を行うためのMath.round()関数について、基本的な使い方から実践的なコード例まで詳しく解説します。
Math.round()関数とは
Math.round()は、JavaScriptに組み込まれている数値を四捨五入するための関数です。引数として与えられた数値を最も近い整数に丸めます。
基本的な使い方
Math.round(数値)使用例
console.log(Math.round(3.4)); // 出力: 3
console.log(Math.round(3.5)); // 出力: 4
console.log(Math.round(3.6)); // 出力: 4
console.log(Math.round(-3.4)); // 出力: -3
console.log(Math.round(-3.5)); // 出力: -3
console.log(Math.round(-3.6)); // 出力: -4小数点以下の桁数を指定した四捨五入
Math.round()は整数への四捨五入のみ対応していますが、小数点以下の桁数を指定して四捨五入したい場合は、以下のような方法があります:
// 小数点第2位で四捨五入する場合
const number = 3.456;
const roundedNumber = Math.round(number * 100) / 100;
console.log(roundedNumber); // 出力: 3.46よくあるエラーと解決方法
1. NaNが返される場合
console.log(Math.round("abc")); // 出力: NaN解決策: 数値に変換できない値を渡した場合はNaNが返されます。必ず数値を渡すようにしましょう。
2. 文字列の数値を扱う場合
// 正しい使用法
console.log(Math.round("3.5")); // 出力: 4
// より安全な方法
console.log(Math.round(Number("3.5"))); // 出力: 4実践的な使用例
1. 価格の計算
const price = 199.99;
const taxRate = 0.1;
const totalPrice = Math.round(price * (1 + taxRate));
console.log(totalPrice); // 出力: 2202. 平均値の計算
const scores = [85.6, 92.3, 78.9];
const average = Math.round(scores.reduce((a, b) => a + b) / scores.length);
console.log(average); // 出力: 86まとめ
- Math.round()は数値を最も近い整数に四捨五入する
- 小数点以下の桁数を指定したい場合は、乗算と除算を組み合わせる
- 文字列の数値も自動的に変換されるが、明示的な変換を使用するのがベストプラクティス
- 計算や統計処理で頻繁に使用される便利な関数
Math.round()を使いこなすことで、数値計算の精度を適切に制御できるようになります。