Help, how can you parse a decimal and ...

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Karim

    Help, how can you parse a decimal and ...

    I am looking for the easiest way to parse a float number.

    X.Y where X=>0 and X <=5 and Y = 0 or Y = 5

    e.g. the number should be one of the following 1 1.0 1.5 2 2.0 2.5 etc.

    I tired using regular expressions, with no luck.

    Thanks,
    Karim
  • Martin Honnen

    #2
    Re: Help, how can you parse a decimal and ...



    Karim wrote:
    [color=blue]
    > I am looking for the easiest way to parse a float number.
    >
    > X.Y where X=>0 and X <=5 and Y = 0 or Y = 5
    >
    > e.g. the number should be one of the following 1 1.0 1.5 2 2.0 2.5 etc.
    >
    > I tired using regular expressions, with no luck.[/color]

    I think
    var numberPattern = /^[0-5]\.[05]$/;
    meets your requirements

    --

    Martin Honnen


    Comment

    • Karim Kabbara

      #3
      Re: Help, how can you parse a decimal and ...

      Martin,

      I tried that, but it only works for 1.0 1.5 2.0 2.5 etc but not 1 2 3 4
      5. Is there another way?

      Thanks,
      Karim

      *** Sent via Developersdex http://www.developersdex.com ***
      Don't just participate in USENET...get rewarded for it!

      Comment

      • Lasse Reichstein Nielsen

        #4
        Re: Help, how can you parse a decimal and ...

        Karim Kabbara <kkabbara@bu.ed u> writes:
        [color=blue]
        > Martin,
        >
        > I tried that, but it only works for 1.0 1.5 2.0 2.5 etc but not 1 2 3 4
        > 5. Is there another way?[/color]

        var numberPattern = /^[0-5](\.[05]|)$/;

        /L
        --
        Lasse Reichstein Nielsen - lrn@hotpop.com
        Art D'HTML: <URL:http://www.infimum.dk/HTML/randomArtSplit. html>
        'Faith without judgement merely degrades the spirit divine.'

        Comment

        • Karim Kabbara

          #5
          Re: Help, how can you parse a decimal and ...

          I bow to you Lasse.Thanks!

          One more addition, I am calculating three fields as-well-as validating.
          I came up with the following code.

          function SumTotal()
          {
          var raps = parseFloat(docu ment.Form.score .value);
          var lrs = parseFloat(docu ment.Form.score 1.value);
          var is = parseFloat(docu ment.Form.score 2.value);

          document.Form.S umTotal1.value = (raps+lrs+is);
          }

          function checknumeric(fi eld)
          {
          pattern = /^[0-5](\.[05]|)$/;

          if(pattern.test (field.value)== false)
          {
          alert("You can only use 1 to 5 and .5");
          }
          }

          I would like to add the Checknumeric with each field being entered.
          Would I use the function with each field or?

          Thanks in advance.

          Karim

          *** Sent via Developersdex http://www.developersdex.com ***
          Don't just participate in USENET...get rewarded for it!

          Comment

          • Lasse Reichstein Nielsen

            #6
            Re: Help, how can you parse a decimal and ...

            Karim Kabbara <kkabbara@bu.ed u> writes:
            [color=blue]
            > One more addition, I am calculating three fields as-well-as validating.
            > I came up with the following code.
            >
            > function SumTotal()
            > {[/color]

            I would make a variable holding the form here, to save time and
            space:
            var form = document.forms['Form'].elements;
            [color=blue]
            > var raps = parseFloat(docu ment.Form.score .value);[/color]

            and then just write
            var raps = parseFloat(form .score.value);
            It is not saving a lot, but I think it is easier to read :)

            You want the values of these three to be between 0 and 5.5 in one-half
            increments. So, you need to check each one.

            I assume you want to check them before converting with parseFloat, to
            rule out inputs of the form "2.5arglebargle ".

            For simplicity, I think I would combine the conversion and check:

            function checkAndConvert (string) {
            if (! (/^[0-5](\.[05])?$/).test(string)) {
            alert("The input '"+string+"' is not between 0 and 5.5 in "+
            "increments of one half");
            return; // returns undefined
            }
            return +string; // converts to number faster than parseFloat.
            }

            Then:

            function SumTotal() {

            var form = document.forms['Form'].elements;

            var raps = checkAndConvert (form.score.val ue);
            var lrs = checkAndConvert (form.score1.va lue);
            var is = checkAndConvert (form.score2.va lue);

            if (raps === undefined ||
            lrs === undefined ||
            is === undefined) {
            return;
            }

            form.SumTotal1. value = (raps+lrs+is);
            }
            [color=blue]
            > I would like to add the Checknumeric with each field being entered.
            > Would I use the function with each field or?[/color]

            In some way, yes.

            /L
            --
            Lasse Reichstein Nielsen - lrn@hotpop.com
            Art D'HTML: <URL:http://www.infimum.dk/HTML/randomArtSplit. html>
            'Faith without judgement merely degrades the spirit divine.'

            Comment

            • Karim Kabbara

              #7
              Re: Help, how can you parse a decimal and ...

              Lasse,

              Thanks again. It works, but I am using the onChange function, so if I
              change each field it calculates all the fields, I need to check the
              validation on !this field then add to the total everytime I change to
              the next field.

              The algorithim would be validate num with rule 0 to 5 with .5
              increments. Then add and total the num.

              Do you think I need an array to do this?

              Regards,
              Karim


              *** Sent via Developersdex http://www.developersdex.com ***
              Don't just participate in USENET...get rewarded for it!

              Comment

              • Karim Kabbara

                #8
                Re: Help, how can you parse a decimal and ...

                Oh yes, I forgot to add, I should use the focus function if the num is
                not valid. So when they change focus and it does not satisfy the
                condition, it place's them back on the field to change.

                Karim



                *** Sent via Developersdex http://www.developersdex.com ***
                Don't just participate in USENET...get rewarded for it!

                Comment

                • Lasse Reichstein Nielsen

                  #9
                  Re: Help, how can you parse a decimal and ...

                  Karim Kabbara <kkabbara@bu.ed u> writes:
                  [color=blue]
                  > Oh yes, I forgot to add, I should use the focus function if the num is
                  > not valid. So when they change focus and it does not satisfy the
                  > condition, it place's them back on the field to change.[/color]

                  This is a dangerous thing to do. It traps people in the field. Good
                  thing it isn't the onblur handler, since this way, they can get away
                  from the input field by trying to leave it twice (the second time,
                  there is have been no change, so the onchange handler doesn't
                  trigger). Don't change it to onblur!

                  You can collect all the values each time you want to update the result,
                  or you can cache them. Here I cache them in an object instead of in an
                  array, together with their sum.

                  ---
                  var values = {raps:0,lrs:0,i s:0,total:0};

                  function checkAndAdd(ele m) {
                  if (!/^[0-5](\.[05])?$/.test(elem.valu e)) {
                  alert("Input illegal: "+elem.valu e);
                  setTimeout(func tion(){elem.foc us();},20); // [1]
                  return;
                  }
                  var value = +elem.value;
                  values.total += value - values[elem.name];
                  values[elem.name] = value;
                  elem.form.eleme nts['SumTotal1'].value = values.total;
                  }
                  ---
                  Then you can call this function from each element:
                  ---
                  <input type="text" name="raps" value="0" onchange="check AndAdd(this)">
                  <input type="text" name="lrs" value="0" onchange="check AndAdd(this)">
                  <input type="text" name="is" value="0" onchange="check AndAdd(this)">
                  ---


                  [1] The delay is for browsers which change the focus to the next
                  element *after* executing the onchange event handler, overriding
                  the focus set in the handler.

                  Hope this works :)
                  /L
                  --
                  Lasse Reichstein Nielsen - lrn@hotpop.com
                  Art D'HTML: <URL:http://www.infimum.dk/HTML/randomArtSplit. html>
                  'Faith without judgement merely degrades the spirit divine.'

                  Comment

                  • Dr John Stockton

                    #10
                    Re: Help, how can you parse a decimal and ...

                    JRS: In article <3f759aa1@olaf. komtel.net>, seen in
                    news:comp.lang. javascript, Martin Honnen <Martin.Honnen@ t-online.de>
                    posted at Sat, 27 Sep 2003 16:11:40 :-[color=blue]
                    >Karim wrote:
                    >[color=green]
                    >> I am looking for the easiest way to parse a float number.
                    >>
                    >> X.Y where X=>0 and X <=5 and Y = 0 or Y = 5
                    >>
                    >> e.g. the number should be one of the following 1 1.0 1.5 2 2.0 2.5 etc.
                    >>
                    >> I tired using regular expressions, with no luck.[/color]
                    >
                    >I think
                    > var numberPattern = /^[0-5]\.[05]$/;
                    >meets your requirements[/color]

                    That seems to fit the description.
                    var numberPattern = /^[1-5](\.[05])?$/; // fits the example

                    I wonder whether he actually wants 5.5 ?

                    --
                    © John Stockton, Surrey, UK. ?@merlyn.demon. co.uk Turnpike v4.00 MIME. ©
                    Web <URL:http://www.merlyn.demo n.co.uk/> - FAQish topics, acronyms, & links.
                    Proper <= 4-line sig. separator as above, a line exactly "-- " (SonOfRFC1036)
                    Do not Mail News to me. Before a reply, quote with ">" or "> " (SonOfRFC1036)

                    Comment

                    • Karim Kabbara

                      #11
                      Re: Help, how can you parse a decimal and ...

                      Yes, I am not trying to get 5.5 my max is 5. Also, I tried the code and
                      I am getting Object not found. The sample is below.Thanks

                      <script language="Javas cript">
                      var values = {raps:0,lrs:0,i sc:0,total:0};

                      function checkAndAdd(ele m) {
                      if (!/^[0-5](\.[05])?$/.test(elem.valu e)) {
                      alert("Input illegal: "+elem.valu e);
                      setTimeout(func tion(){elem.foc us();},20); // [1]
                      return;
                      }
                      var value = +elem.value;
                      values.total += value - values[elem.name];
                      values[elem.name] = value;
                      elem.form.eleme nts['SumTotal1'].value = values.total;
                      }


                      </script>
                      <table>
                      <tr>
                      <td>RAPS</td>
                      <td><input maxlength="10" size="10" value="" name="raps"
                      onchange="check andadd(this)"></td>
                      </tr>

                      <tr>
                      <td >LRS</td>
                      <td ><input maxlength="10" size="10" value="" name="lrs"
                      onchange="check andadd(this)"></td>
                      </tr>

                      <tr>
                      <td >IS</td>
                      <td ><input maxlength="10" size="10" value="" name="isc"
                      onchange="check andadd(this)"></td>
                      </tr>

                      <tr>
                      <td align="right">< span style="FONT-SIZE: 12pt">Overall
                      Score (0-15):
                      <o:p></o:p>
                      </span> </td>
                      <td ><strong><inp ut id="SumTotal1" readonly name="SumTotal1 "
                      style="WIDTH: 79px; HEIGHT: 22px"

                      size="10"></strong></td>
                      </tr>

                      </table>



                      *** Sent via Developersdex http://www.developersdex.com ***
                      Don't just participate in USENET...get rewarded for it!

                      Comment

                      • Lasse Reichstein Nielsen

                        #12
                        Re: Help, how can you parse a decimal and ...

                        Karim Kabbara <kkabbara@bu.ed u> writes:
                        [color=blue]
                        > Yes, I am not trying to get 5.5 my max is 5. Also, I tried the code and
                        > I am getting Object not found. The sample is below.Thanks[/color]
                        [color=blue]
                        > <script language="Javas cript">[/color]

                        Use
                        <script type="text/javascript">
                        instead. The type attribute is required in HTML 4.
                        [color=blue]
                        > var values = {raps:0,lrs:0,i sc:0,total:0};
                        >
                        > function checkAndAdd(ele m) {
                        > if (!/^[0-5](\.[05])?$/.test(elem.valu e)) {[/color]

                        If you didn't want 5.5, the regular expression would have to change, e.g.,
                        if (!/^(([0-4](\.[05])?)|(5(\.0)?))$/.test(elem.valu e)) {

                        or perhaps using a simple comparison with the regular expression:

                        if (!/^[0-5](\.[05])?$/.test(elem.valu e) || elem.value > 5) {[color=blue]
                        > elem.form.eleme nts['SumTotal1'].value = values.total;[/color]

                        There is no form around your input elements (which I assumed there
                        would be), so this fails. Have to change it to:

                        document.getEle mentById("SumTo tal1").value = values.total;
                        [color=blue]
                        > onchange="check andadd(this)"></td>[/color]

                        Javascript is case sensitive. This should be

                        onchange="check AndAdd(this)"></td>

                        with capital A's.
                        This goes for all three inputs.
                        [color=blue]
                        > <td ><strong><inp ut id="SumTotal1" readonly name="SumTotal1 "
                        > style="WIDTH: 79px; HEIGHT: 22px"[/color]

                        You don't need the name attribute on this input. Also, the strong tag
                        isn't affecting the contents of the input in my browser. You would
                        probably get a better result by adding "font-weight:bold;" to the style
                        attribute.

                        /L
                        --
                        Lasse Reichstein Nielsen - lrn@hotpop.com
                        Art D'HTML: <URL:http://www.infimum.dk/HTML/randomArtSplit. html>
                        'Faith without judgement merely degrades the spirit divine.'

                        Comment

                        Working...