Monday, 7 May 2012

Javascript Rounding of Numbers


Number rounding so important for many mathematical, financial, etc, calculations. Example below simple show how to round a fractional number.

  1. The parseFloat (value) will convert the number into a fractional number and make sure is a number.
  2. Get the decimal part from the number (converted - parseInt (converted, 10)).
  3. Use conditional statement to check the decimal part – if the decimal value is 0 then assign the value as it is, decimal value is 5 then add 1 to the number, for all other cause add .5 to number
<html>
<head>
<title>Javascript Round Number</title>
<script>
function RoundNumber(){
 var value;
 value  = document.all("txtFractionNo").value;
 var converted = parseFloat(value); //Make sure we have a number
 var decimal = (converted - parseInt(converted, 10));
 decimal = Math.round(decimal * 10);
 if (decimal == 0) {
   document.all("txtRoundNo").value =value  ;
 }
 else if (decimal > 5) {
   document.all("txtRoundNo").value =parseInt(converted, 10)+1;
 }
 else{
document.all("txtRoundNo").value = (parseInt(converted, 10)+0.5);
 }
}
</script>
</head>
<body>
<span>Number in Fraction:</span>&nbsp<input type="text" id="txtFractionNo" />
<br/>
<span>Rounded Number:&nbsp&nbsp&nbsp</span><input type="text" id="txtRoundNo" />
<input type="button" id="btnClick" name="Convert" value="Convert"
onclick="javascript:RoundNumber();"/>
</body>
</html>

No comments:

Post a Comment