どうも、ちょげ(@chogetarou)です。
整数部分の桁数を指定して数値のNの位を四捨五入する方法を紹介します。
方法

桁数を指定して数値のNの位を四捨五入するには、Math.round()を使います。
まず、Math.round()を呼び出します。
Math.round()の引数に、数値を10のN乗で割った値を指定します。
(Nは整数部分の桁数)
そして、Math.round()の結果に10のN乗を掛けます。
//x=10のN乗
Math.round(number / x) * x;
上記の掛け算は、数値の指定した桁数を四捨五入した数値を返します。
使用例
function round(num, digits) {
const x = Math.pow(10, digits);
return Math.round(num / x) * x;
}
var num = 1521;
var num2 = 18861;
var num3 = 125749;
const result = round(num, 1)
const result2 = round(num2, 2)
const result3 = round(num3, 3)
console.log(result);
console.log(result2);
console.log(result3);
出力:
1520
18900
126000
コメント