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>
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>
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/.
Go To Page: 1 2 Articles in this Topic Discussions in this Topic |