在 JavaScript 中,将数字四舍五入到 N 位小数的典型方法是:
function roundNumber(num, dec) {
return Math.round(num * Math.pow(10, dec)) / Math.pow(10, dec);
}
function roundNumber(num, dec) {
return Math.round(num * Math.pow(10, dec)) / Math.pow(10, dec);
}
console.log(roundNumber(0.1 + 0.2, 2));
console.log(roundNumber(2.1234, 2));
但是,这种方法最多会舍入到N 个小数位,而我希望总是舍入到 N 个小数位。例如,“2.0”将四舍五入为“2”。
有任何想法吗?