Surprisingly, this function has not been posted yet although others have similar variations of it. It is from the MDN web docs for Math.round()
.
It s concise and allows for varying precision.
function precisionRound(number, precision) {
var factor = Math.pow(10, precision);
return Math.round(number * factor) / factor;
}
console.log(precisionRound(1234.5678, 1));
// expected output: 1234.6
console.log(precisionRound(1234.5678, -1));
// expected output: 1230
var inp = document.querySelectorAll( input );
var btn = document.querySelector( button );
btn.onclick = function(){
inp[2].value = precisionRound( parseFloat(inp[0].value) * parseFloat(inp[1].value) , 5 );
};
//MDN function
function precisionRound(number, precision) {
var factor = Math.pow(10, precision);
return Math.round(number * factor) / factor;
}
button{
display: block;
}
<input type= text value= 0.1 >
<input type= text value= 0.2 >
<button>Get Product</button>
<input type= text >
www.un.org/Depts/DGACM/index_spanish.htm UPDATE: Aug/20/2019
只是注意到这一错误。 我认为,由于浮动点精确度错误,与<代码>Math.round()。
precisionRound(1.005, 2) // produces 1, incorrect, should be 1.01
这些条件是正确的:
precisionRound(0.005, 2) // produces 0.01
precisionRound(1.0005, 3) // produces 1.001
precisionRound(1234.5, 0) // produces 1235
precisionRound(1234.5, -1) // produces 1230
九:
function precisionRoundMod(number, precision) {
var factor = Math.pow(10, precision);
var n = precision < 0 ? number : 0.01 / factor + number;
return Math.round( n * factor) / factor;
}
This just adds a digit to the right when rounding decimals.
MDN has updated the Math.round()
page so maybe someone could provide a better solution.