Partners
Web Hosting
We've partnered with HostGator for reliable, affordable hosting starting at $3.95/mon. Use coupon code "javascriptkit25" for 25% off any package.

Number rounding in JavaScriptSo trivial a task to us humans, almost so to JavaScript as well. Round up your brain cells as we explore number rounding in the language! Basic ideaJavaScript helps lay the foundation for rounding off numbers with the following method: Math.round(x) Using it, any supplied argument is rounded off to the nearest integer, and using the ".5" up rule. For example: Math.round(25.9) //returns 26 Math.round(25.2) //returns 25 Math.round(2.58) //returns 3 If purging numbers of decimals is all that you require, class dismissed! Taking things a few decimals furtherWant to display $25 in standard currency format? How about PI to finity and not beyond? Formatting numbers to specific decimal points entails still Math.round(), but padded with a little multiplication and division. See if you can identify the magic formula involved, with the below examples: var original=28.453 1) //round "original" to two decimals var result=Math.round(original*100)/100 //returns 28.45 2) // round "original" to 1 decimal var result=Math.round(original*10)/10 //returns 28.5 3) //round 8.111111 to 3 decimals var result=Math.round(8.111111*1000)/1000 //returns 8.111 In case you haven't picked up on it, the formula to round any number to x decimal points is: 1) Multiple the original number by 10^x (10 to the power
of x) Ahh, pre Algebra class all over again... 