Sunday, August 29, 2010

How to round numbers in JavaScript

JavaScript number rounding is done using Math.round
This will round a given number to the nearest whole number

<script type="text/javascript">

var number = 100.58;
number = Math.round(number);
alert(number); //101

</script>


If you do need some decimal points preserved, following code will round the number to the nearest tenth.

<script type="text/javascript">

var number = 100.58;
number = Math.round(number*10)/10;
alert(number); //100.6

</script>


No comments:

Post a Comment