Rounding Numbers in JavaScript

A very common question while dealing with Math methods in JavaScript is to round numbers. JavaScript provides 3 rounding methods: round(), ceil() and floor()

round() – rounds a number up if decimal part is >= .5, else rounds down

ceil() - rounds a number up to the nearest whole number and removes decimal

floor() – rounds a number down to the nearest whole number and removes decimal

Here’s an example:

<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>Math Rounding by DevCurry.com</title>
</head>
<body>
<script type="text/javascript">
function callRounding(num) {
document.write("Original value: " + num + "</br>");
document.write("Using round(): " + Math.round(num) + "</br>");
document.write("Using ceil(): " + Math.ceil(num) + "</br>");
document.write("Using floor(): " + Math.floor(num) + "</br>");
}
</script>
<input id="btn1" type="button" value="Example 1"
onClick="callRounding(2.12)" />
<input id="btn2" type="button" value="Example 2"
onClick="callRounding(2.62)" />
<input id="btn3" type="button" value="Example 3"
onClick="callRounding(-2.62)" />
</body>
</html>


OUTPUT

image

See a Live Demo



Will you give this article a +1 ? Thanks in advance


About The Author

Suprotim Agarwal
Suprotim Agarwal, ASP.NET Architecture MVP (Microsoft Most Valuable Professional) works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He is the Editor of a Developer Magazine called DNC Magazine. He has also written two EBooks 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook

Follow him on twitter @suprotimagarwal

No comments: