Method to round numbers precision in Javascript
Matho.round(), Math.ceil(), Math.floor(), Number.prototype.toFixed() methods are used to round off decimal precision in javascript. Example is created below with all above rounding methods of javascript.
|
var number = 1982.8389;
document.write(Math.round(number)+"<br />");
document.write(Math.ceil(number)+"<br />");
document.write(Math.floor(number)+"<br />");
//Round to two decimal values
document.write(number.toFixed(2)+"<br />");
//Adding zero's to unavailable precision
document.write(number.toFixed(6)+"<br />");
//default is zero
document.write(number.toFixed()+"<br />");
//1983 round to -1 then 1980
//1980 round to -1 then 8 is given 1 to 19 so 2000
document.write(number.toFixed(-2)+"<br />");
|