Showing posts with label Math. Show all posts
Showing posts with label Math. Show all posts

Wednesday, October 13, 2010

How to round numbers in JavaScript?

You can use Math Object or Bitwise Operator for round a number:

round(a) - Returns the value of a to the nearest integer. If the values decimal value is .5 or greater the next highest integer value is returned otherwise the next lowest integer is returned.


floor(a) - Rounds the passed value down to the previous integer. If the passed value is already an integer the returned value is the same as the passed value.


ceil(x) - Rounds up the value of "a" to the next integer. If the value is a already whole number, the return value will be the same as the passed value.

<script type="text/javascript">
var original=28.453;
//round "original" to the nearest integer
var result = Math.round(original);  //returns 28
//other way
var result = original >> 0;  //returns 28

//round "original" to  down to the previous integer
var result = Math.floor(original);  //returns 28
//round "original" to  up to the next integer
var result = Math.ceil(original);  //returns 29

//round "original" to two decimals
var result = Math.round(original*100)/100;  //returns 28.45
// other way
var result = (original *100 >> 0) *0.01;  //returns 28.45
</script>