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」に丸められます。
何か案は?