To get the desired number of decimal precision, Math.round requires a multiplication followed by a division (the "multiply-and-divide" method).
This "multiply-and=divide" method can produce a roundoff error, but apparently it can be avoided by instead raising then lowering the number's exponent (call this the "exponent" method).
The "multiply-and-divide" method:
Math.round(num*100)/100
The "exponent" method:
Number(Math.round(num+'e2') + 'e-2')
Try the snippet below with num1 = 1.005, num2 = 1, decimals = 2. The "multiply-and-divide" method gets it wrong, the "exponent" method gets it right.
/* the "multiply-and-divide" rounding method */
function roundmult(value, decimals) {
let multiplier = 1;
for (let i = 0; i < decimals; i++) {
multiplier *= 10;
}
return Math.round(value * multiplier) / multiplier;
}
/* the "exponent" rounding method */
function roundexp(value, decimals) {
return Number(Math.round(value + 'e' + decimals) + 'e-' + decimals);
}
function testIt() {
let decimals = +(document.getElementById("decimals").value);
let num1 = +(document.getElementById("num1").value);
let num2 = +(document.getElementById("num2").value);
let product = num1 * num2;
let resultmult = roundmult(product, decimals);
document.getElementById("multdiv").innerText = resultmult;
let resultexp = roundexp(product, decimals);
document.getElementById("exponent").innerText = resultexp;
}
<h1>
Math.round() Test
</h1>
<label for="num1">num1</label>
<input id="num1" type="number"> times
<label for="num2">num2</label>
<input id="num2" type="number"><br />
<label for="decimals">decimal places:</label>
<input id="decimals" type="number"><br /><br />
<button id="doit" onclick="testIt();">
Round it!
</button><br /><br /> The "multiply and divde" method result is: <span id="multdiv"></span>
<br /><br /> The "exponent" method result is: <span id="exponent"></span>