[JavaScript]小数点の桁数を指定して四捨五入するには?

JavaScript

どうも、ちょげ(@chogetarou)です。

小数点の桁数を指定して四捨五入する方法を紹介します。

スポンサーリンク

方法

インターフェース, インターネット, プログラム, ブラウザ, Www

小数点の桁数を指定して四捨五入するには、Math.round()を使います。

まず、Math.round()を呼び出します。

Math.round()の引数に、数値を10のN乗を掛けた値を指定します。
(Nは小数点の桁数を−1した値)

そして、Math.round()の結果を10のN乗で割ります。

//x=10をN乗した値(Nは小数点の桁数を−1した値)
const result = Math.round(number * x) / x

上記の割り算は、数値の指定した小数点の桁数を四捨五入した数値を返します。

使用例

function roundNumber(num, digits) {
    const n = Math.pow(10, digits - 1);
    return Math.round(num * n) / n;
}

var num = 1.521;
var num2 = 2.8861;
var num3 = 3.25749;

const result = roundNumber(num, 2);
const result2 = roundNumber(num2, 3);
const result3 = roundNumber(num3, 4);

console.log(result);
console.log(result2);
console.log(result3);
出力:
1.5
2.89
3.257

コメント

タイトルとURLをコピーしました