Pages

Monday, February 20, 2012

How to round numbers in java Script


Option1 : Math.Round()

Jave Script For rounding the numbers to required decimals ...

<script language="javascript" type="text/javascript">
function roundNumber(rnum, rlength) { // Arguments: number to round, number of decimal places
var newnumber = Math.round(rnum*Math.pow(10,rlength))/Math.pow(10,rlength);
document.roundform.numberfield.value = parseFloat(newnumber); // Output the result to the form field (change for your
purposes)
}
</script>


Simple HTM For for Rounding the numbers 

<form name="roundform">
<table border="0" cellspacing="0" cellpadding="5">
<tr>
<td>Round:</td>
<td><input type="text" name="numberfield" value="">
to
<input name="decimalfield" type="text" value="2" size="3">
decimal places</td>



Option 2: toFixed (beta)

Java Script
<script type="text/javascript">
function roundNumber(number, decimals) { // Arguments: number to round, number of decimal places
var newnumber = new Number(number+'').toFixed(parseInt(decimals));
document.roundform.roundedfield.value = parseFloat(newnumber); // Output the result to the form field (change for your purposes)
}
</script>

Sample HTML Form 

<form name="roundform">
<table border="0" cellspacing="0" cellpadding="5">
<tr>
<td>Round:</td>
<td><input type="text" name="numberfield" value="">
to
<input name="decimalfield" type="text" value="2" size="3">
decimal places</td>













No comments:

Post a Comment