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
See a Live Demo
Tweet
No comments:
Post a Comment