JavaScript四捨五入の基本 - Math.roundの使い方を初心者向けに解説
JavaScript Math.roundメソッドの基本的な使い方から応用テクニックまで詳しく解説。小数点以下の桁数指定、価格計算、統計処理での実践的な使用例を初心者向けに分かりやすく説明します。
JavaScript四捨五入の基本 - Math.roundの使い方を初心者向けに解説
みなさん、JavaScriptで数値計算をしていて困ったことありませんか?
「小数点以下を四捨五入したい」 「価格計算で端数を整えたい」 「統計データを見やすく表示したい」
こんな場面に遭遇することがあるかもしれませんね。
JavaScriptのMath.roundメソッドは、数値を最も近い整数に四捨五入するための基本的な関数です。 この記事では、Math.roundメソッドについて基本的な使い方から実践的な応用テクニックまで詳しく解説します。
小数点以下の桁数指定、価格計算、統計処理での活用方法を、実際のコード例を交えて初心者向けに分かりやすく説明していきます。
Math.roundって何だろう?
四捨五入の基本
四捨五入は、小数点以下の数値を最も近い整数に丸める処理です。
0.5以上は切り上げ、0.5未満は切り捨てというルールで動作します。 例えば、4.3は4に、4.7は5になります。
// Math.roundの基本的な使い方console.log(Math.round(4.3)); // 4console.log(Math.round(4.5)); // 5console.log(Math.round(4.7)); // 5
このように、小数点以下を見て一番近い整数にしてくれます。
負の数の場合も同じように動作します。
console.log(Math.round(-4.3)); // -4console.log(Math.round(-4.5)); // -4console.log(Math.round(-4.7)); // -5
ちょっと注意が必要なのは、-4.5が-4になることです。 これは0に近い方向に丸められるためです。
基本的な使い方
実際にMath.roundを使ってみましょう。
let originalNumber = 3.14159;let roundedNumber = Math.round(originalNumber);
console.log(`元の数値: ${originalNumber}`); // 3.14159console.log(`四捨五入後: ${roundedNumber}`); // 3
価格計算での例も見てみましょう。
let price = 198.6;let roundedPrice = Math.round(price);console.log(`商品価格: ${roundedPrice}円`); // 199円
このように、端数のある価格を整数にできます。
複数の値を一度に処理
配列の値をまとめて四捨五入することもできます。
let numbers = [3.2, 4.8, 5.5, 6.1, 7.9];let roundedNumbers = numbers.map(num => Math.round(num));
console.log("元の数値:", numbers);console.log("四捨五入後:", roundedNumbers);// [3, 5, 6, 6, 8]
map
を使うことで、配列の全要素を一度に処理できます。
小数点以下の桁数を指定してみよう
特定の桁数で四捨五入
Math.roundは整数に丸めますが、小数点以下の特定の桁数で四捨五入したい場合もありますよね。
そんなときは、掛け算と割り算を組み合わせます。
// 小数点第2位で四捨五入する関数function roundToFixed(num, digits = 0) { let multiplier = Math.pow(10, digits); return Math.round(num * multiplier) / multiplier;}
let pi = 3.14159;
console.log(roundToFixed(pi, 0)); // 3(整数)console.log(roundToFixed(pi, 1)); // 3.1console.log(roundToFixed(pi, 2)); // 3.14console.log(roundToFixed(pi, 3)); // 3.142
この関数を使えば、好きな桁数で四捨五入できます。
実用的な例も見てみましょう。
let temperature = 23.456789;console.log(`気温: ${roundToFixed(temperature, 1)}°C`); // 23.5°C
let exchangeRate = 149.7834;console.log(`為替レート: ${roundToFixed(exchangeRate, 2)}`); // 149.78
日常的な数値表示がきれいになりますね。
toFixed()との違い
似たような機能でtoFixed()
メソッドがあります。
違いを確認してみましょう。
let number = 3.14159;
// Math.round + 計算による方法(数値が返される)let roundedNumber = Math.round(number * 100) / 100;console.log(roundedNumber); // 3.14(数値型)console.log(typeof roundedNumber); // "number"
// toFixed()メソッド(文字列が返される)let fixedString = number.toFixed(2);console.log(fixedString); // "3.14"(文字列型)console.log(typeof fixedString); // "string"
toFixed()
は文字列を返すので、計算に使う場合は数値に戻す必要があります。
let fixedNumber = parseFloat(number.toFixed(2));console.log(fixedNumber); // 3.14(数値型)
用途に応じて使い分けましょう。
実際の開発で使ってみよう
価格計算システム
ショッピングサイトでよくある価格計算を作ってみましょう。
class PriceCalculator { constructor(taxRate = 0.1) { this.taxRate = taxRate; } // 税込み価格を計算 calculateTaxIncluded(price) { let taxIncluded = price * (1 + this.taxRate); return Math.round(taxIncluded); } // 割引価格を計算 calculateDiscounted(price, discountRate) { let discounted = price * (1 - discountRate); return Math.round(discounted); } // 送料計算 calculateShipping(weight, ratePerKg = 200) { let shippingCost = weight * ratePerKg; return Math.round(shippingCost); }}
このクラスを使ってみましょう。
let calculator = new PriceCalculator(0.1); // 10%の消費税
let productPrice = 1980;console.log(`商品価格: ${productPrice}円`);console.log(`税込み価格: ${calculator.calculateTaxIncluded(productPrice)}円`);console.log(`20%割引価格: ${calculator.calculateDiscounted(productPrice, 0.2)}円`);
実際の価格計算がスムーズにできます。
統計データの処理
テストの成績や売上データなどの統計計算にも活用できます。
class StatisticsCalculator { constructor(data) { this.data = data.filter(num => !isNaN(num)); // 無効な値を除外 } // 平均値 mean() { if (this.data.length === 0) return 0; let sum = this.data.reduce((acc, num) => acc + num, 0); return Math.round((sum / this.data.length) * 100) / 100; } // 中央値 median() { if (this.data.length === 0) return 0; let sorted = [...this.data].sort((a, b) => a - b); let middle = Math.floor(sorted.length / 2); if (sorted.length % 2 === 0) { return Math.round(((sorted[middle - 1] + sorted[middle]) / 2) * 100) / 100; } else { return sorted[middle]; } }}
使用例を見てみましょう。
let testScores = [85, 92, 78, 95, 88, 91, 87, 83, 94, 89];let stats = new StatisticsCalculator(testScores);
console.log("平均点:", stats.mean()); // 88.2console.log("中央値:", stats.median()); // 88.5
統計データがきれいに表示されます。
ゲームスコアの管理
ゲームのスコア計算にも応用できます。
class GameScoreManager { constructor() { this.scores = []; this.multipliers = { easy: 1.0, normal: 1.5, hard: 2.0, expert: 3.0 }; } // スコア追加 addScore(baseScore, difficulty = 'normal', timeBonus = 0) { let multiplier = this.multipliers[difficulty] || 1.0; let finalScore = Math.round((baseScore * multiplier) + timeBonus); this.scores.push(finalScore); return finalScore; } // 平均スコア計算 getAverageScore() { if (this.scores.length === 0) return 0; let total = this.scores.reduce((sum, score) => sum + score, 0); return Math.round(total / this.scores.length); } // ハイスコア取得 getHighScore() { if (this.scores.length === 0) return 0; return Math.max(...this.scores); }}
実際に使ってみましょう。
let gameScore = new GameScoreManager();
// スコア追加gameScore.addScore(1500, 'easy', 200); // 1700点gameScore.addScore(2000, 'normal', 500); // 3500点gameScore.addScore(1800, 'hard', 300); // 3900点
console.log("ハイスコア:", gameScore.getHighScore()); // 3900console.log("平均スコア:", gameScore.getAverageScore()); // 3033
ゲームの成績管理が簡単にできます。
注意点と対策
文字列との混同
よくある間違いとして、文字列を直接Math.roundに渡してしまうことがあります。
let userInput = "3.7";
// 間違い:文字列をそのまま使用// console.log(Math.round(userInput)); // NaN
// 正しい:数値に変換してから使用console.log(Math.round(parseFloat(userInput))); // 4console.log(Math.round(Number(userInput))); // 4
安全な変換関数を作ってみましょう。
function safeRound(value, decimals = 0) { let num = parseFloat(value); if (isNaN(num)) { console.warn(`無効な数値: ${value}`); return 0; } let multiplier = Math.pow(10, decimals); return Math.round(num * multiplier) / multiplier;}
この関数なら、文字列でも安全に処理できます。
浮動小数点数の精度問題
JavaScriptでは、小数の計算で精度の問題が発生することがあります。
console.log(0.1 + 0.2); // 0.30000000000000004console.log(Math.round((0.1 + 0.2) * 10) / 10); // 0.3
この問題を考慮した関数を作ってみましょう。
function preciseRound(num, decimals = 0) { // Number.EPSILON を使用した四捨五入 let multiplier = Math.pow(10, decimals); return Math.round((num + Number.EPSILON) * multiplier) / multiplier;}
console.log("通常:", Math.round((0.1 + 0.2) * 100) / 100); // 0.3console.log("精度考慮版:", preciseRound(0.1 + 0.2, 2)); // 0.3
より正確な計算ができるようになります。
負の数での予期しない動作
負の数での四捨五入は注意が必要です。
let negativeNumbers = [-2.7, -2.5, -2.3];
console.log("=== 負の数の四捨五入 ===");negativeNumbers.forEach(num => { console.log(`${num} → ${Math.round(num)}`);});
// -2.7 → -3// -2.5 → -2 ← 注意:-3ではない// -2.3 → -2
-2.5が-2になることに注意しましょう。 これは0に近い方向に丸められるためです。
まとめ
JavaScript Math.roundメソッドについて詳しく解説しました。
基本的な機能
- 整数への四捨五入: 最も近い整数に丸める
- シンプルな構文: Math.round(数値)
- 標準的な動作: 0.5以上で切り上げ
実践的な応用
- 価格計算: 税込み価格、割引価格の算出
- 統計処理: 平均値、中央値の計算
- ゲームスコア: スコア計算とランキング
高度なテクニック
- 小数点桁数指定: 乗除算による桁数制御
- 精度問題対策: Number.EPSILONの活用
- エラーハンドリング: 安全な数値変換
注意点とベストプラクティス
- 文字列から数値への適切な変換
- 浮動小数点数の精度問題への対応
- 負の数での予期しない動作の理解
Math.roundを適切に活用することで、より正確で信頼性の高い数値計算を行うJavaScriptアプリケーションが作れるようになります。
まずは基本的な使い方から始めて、だんだんと高度なテクニックも取り入れてみましょう。 きっと、もっと正確で使いやすい数値処理機能が作れるようになりますよ。
ぜひ今日から、これらの知識を活用してより精密な数値処理機能を実装してみませんか?