Freelance Writing Jobs | Today's Articles | Sign In

 
Browse Sections

Truncating Real Numbers


<script language="JavaScript1.2">
   var str = "" + 33.456789;
   var re = /\d*.\d\d/;

   var arrValue = re.exec (str);
   alert (arrValue[0]);
</script>



Improvements:

Try to run the code as it is and see the power of JavaScript yourself. The string that will match is 33.45. This code will not handle special conditions, for example giving it only 33.0 will not have the desired effect. There are two possible solutions: write your own algorithm that handles these special conditions OR form a complex pattern. I would prefer a mixed strategy.

A generic way to handle all cases, except negative number is presented below. We define a text box and a button. The user can type in a number (with decimal point) and click the button. The onClick event shows the cut off value.

<html>
<head>
<script language="JavaScript1.2">

function onClickRoundOff() {
   var input = example.input.value;
   if (input.indexOf (".") == -1) input += ".00";
   else input += "00";

   var pattern = /\d*.\d\d/;
   var result = pattern.exec (input);
   if (result != null) alert (result[0]);
}
</script>
</head>

<body>
<center>
<form name="example">
   <input type="text" name="input" value="">
   <input type="button" value="Round Off" onClick="onClickRoundOff()">
</form>
</center>
</body>
</html>



Home Assignment:

If you have really understood the above concepts, try to change the pattern to handle the optional positive or negative sign. Hint: Use the pattern /(+|-)?\d*.\d\d/.

The copyright of the article Truncating Real Numbers in JavaScript is owned by Muhammad Ali Shah. Permission to republish Truncating Real Numbers in print or online must be granted by the author in writing.

Go To Page: 1 2

Articles in this Topic    Discussions in this Topic

;