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






About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

No comments: