Changing strings to numbers(easy...maybe)

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

    Changing strings to numbers(easy...maybe)

    Hi,

    Im trying to add 3 numbers together, instead of getting 1+2+3=6, I'm
    getting 123, how could I remedy this.

    ManyThanks in advance

    Michael

    <html>
    <head>
    <title>Summatio n Template File</title>
    <meta http-equiv="Content-Type" content="text/html;
    charset=iso-8859-1">
    <script language="JavaS cript">
    function addUp() {
    var a,b,c,sum;
    a = document.fred.a aa.value; // extract the string of text typed into
    the input box
    b = document.fred.b bb.value;
    c = document.fred.c cc.value;
    // the problem is on the next line, all the other lines are OK and
    shouldn't be changed
    sum =a+b+c ;
    window.alert("T he sum is "+sum);
    }
    </script>
    </head>

    <body bgcolor="#FFFFF F" text="#000000">
    <form name="fred">
    <input type="text" name="aaa" size="5">
    <input type="text" name="bbb" size="5">
    <input type="text" name="ccc" size="5">
    <input type="button" value="Sum Data" onClick="addUp( );">
    </form>
    </body>
    </html>
  • Kae Verens

    #2
    Re: Changing strings to numbers(easy... maybe)

    MickG wrote:
    [color=blue]
    > Hi,
    >
    > Im trying to add 3 numbers together, instead of getting 1+2+3=6, I'm
    > getting 123, how could I remedy this.[/color]

    use parseInt(number ) to get a number

    Kae

    Comment

    • Evertjan.

      #3
      Re: Changing strings to numbers(easy... maybe)

      MickG wrote on 28 feb 2005 in comp.lang.javas cript:
      [color=blue]
      > Im trying to add 3 numbers together, instead of getting 1+2+3=6, I'm
      > getting 123, how could I remedy this.
      >[/color]

      var a='1' // string !
      var b='2' // string !
      var c='3' // string !

      r = a + b + c

      alert(r) // returns string 123

      r = +a + +b + +c

      alert(r) // returns number 6

      r = 1*a + 1*b + 1*c

      alert(r) // returns number 6


      --
      Evertjan.
      The Netherlands.
      (Replace all crosses with dots in my emailaddress)

      Comment

      • Douglas Crockford

        #4
        Re: Changing strings to numbers(easy... maybe)

        > I'm trying to add 3 numbers together, instead of getting 1+2+3=6, I'm[color=blue]
        > getting 123, how could I remedy this.[/color]
        [color=blue]
        > a = document.fred.a aa.value; // extract the string of text typed into
        > // the input box
        > b = document.fred.b bb.value;
        > c = document.fred.c cc.value;
        > // the problem is on the next line, all the other lines are OK and
        > // shouldn't be changed
        > sum =a+b+c ;[/color]

        sum = (+a) + (+b) + (+c);

        See http://www.crockford.com/javascript/survey.html

        If you leave out the parens, it could look like

        sum = +a++b++c;

        which would be very bad. It is better to be clear.

        Comment

        • Michael Winter

          #5
          Re: Changing strings to numbers(easy... maybe)

          Kae Verens wrote:

          To the OP: In future please read the FAQ before posting. See
          <URL:http://jibbering.com/faq/>.

          [snip]
          [color=blue]
          > use parseInt(number ) to get a number[/color]

          parseInt(number , radix)

          is almost always preferred.

          There are faster ways to coerce a string to a number, namely unary plus:

          +str1 + +str2

          With the brief snippet shown by the OP, I'd suggest checking the
          format of the user input before using it. Whilst parseInt will behave
          somewhat sensibly when parsing a non-numeric string, it isn't very
          useful to start adding NaNs.

          function isInteger(s) {return /^(0|[1-9]\d*)$/.test(s);}

          function sum(f) {
          var e = f.elements,
          a = e['a'],
          b = e['b'],
          c = e['c'];

          if(!isInteger(a )) {
          /* Instruct user that input A is invalid. */
          return false;
          }
          if(!isInteger(b )) {
          /* Instruct user that input B is invalid. */
          return false;
          }
          if(!isInteger(c )) {
          /* Instruct user that input C is invalid. */
          return false;
          }
          e['total'].value = +a + +b + +c;
          }

          <form action="">
          <input type="text" name="a">
          <input type="text" name="b">
          <input type="text" name="c">
          <input type="text" name="total">
          <input type="button" value="Sum" onclick="sum(th is.form);">
          </form>

          Mike

          --
          Michael Winter
          Replace ".invalid" with ".uk" to reply by e-mail.

          Comment

          • Randy Webb

            #6
            Re: Changing strings to numbers(easy... maybe)

            Kae Verens wrote:
            [color=blue]
            > MickG wrote:
            >
            >[color=green]
            >>Hi,
            >>
            >>Im trying to add 3 numbers together, instead of getting 1+2+3=6, I'm
            >>getting 123, how could I remedy this.[/color]
            >
            >
            > use parseInt(number ) to get a number[/color]

            No. You use the unary + to get a number, depending on what you define as
            a number.

            parseInt('08') is a very prime example of the flaw of parseInt when not
            used with a radix.

            --
            Randy
            comp.lang.javas cript FAQ - http://jibbering.com/faq & newsgroup weekly

            Comment

            • mike

              #7
              Re: Changing strings to numbers(easy... maybe)

              Or this !!

              sum = (a-0) + (b-0) + (c-0);

              Comment

              • RobG

                #8
                Re: Changing strings to numbers(easy... maybe)

                MickG wrote:[color=blue]
                > Hi,
                >
                > Im trying to add 3 numbers together, instead of getting 1+2+3=6, I'm
                > getting 123, how could I remedy this.
                >[/color]

                <URL:http://www.jibbering.c om/faq/#FAQ4_21>



                --
                Rob

                Comment

                • Randy Webb

                  #9
                  Re: Changing strings to numbers(easy... maybe)

                  mike wrote:[color=blue]
                  > Or this !!
                  >
                  > sum = (a-0) + (b-0) + (c-0);
                  >[/color]

                  No, you should read this groups FAQ first.

                  Had you done that, you would have prevented at least two problems with
                  your post. I will leave it to you as an exercise to determine what those
                  problems are.

                  --
                  Randy
                  comp.lang.javas cript FAQ - http://jibbering.com/faq & newsgroup weekly

                  Comment

                  • Dr John Stockton

                    #10
                    Re: Changing strings to numbers(easy... maybe)

                    JRS: In article <1a9c775a.05022 81145.4411e7c1@ posting.google. com>,
                    dated Mon, 28 Feb 2005 11:45:00, seen in news:comp.lang. javascript,
                    MickG <mickg77@hotmai l.com> posted :
                    [color=blue]
                    >Im trying to add 3 numbers together,[/color]

                    No, you are not. You are adding 3 strings (probably; at least one is a
                    string).
                    [color=blue]
                    > instead of getting 1+2+3=6, I'm
                    >getting 123, how could I remedy this.[/color]

                    By reading the newsgroup FAQ.



                    Michael : Matches to /^-\d+$/ are integers too.


                    Douglas :[color=blue]
                    > sum = (+a) + (+b) + (+c);
                    >If you leave out the parens, it could look like
                    > sum = +a++b++c;[/color]

                    When I leave them out, it looks like
                    sum = +a + +b + +c;


                    All:

                    "Numeric strings" commonly come from reading input controls.

                    In such cases it is often good to write

                    var Wotsit = + nameofWotsitcon trol.value
                    var Al = + nameofAlcontrol .value
                    var ...
                    // expression(s) using Wotsit /et al/

                    Firstly, the desired values are obtained in the desired form; after
                    that, they are used in expressions which are not cluttered by control
                    addressing. The gain on clarity will generally outweigh any minor loss
                    in performance.

                    --
                    © John Stockton, Surrey, UK. ?@merlyn.demon. co.uk Turnpike v4.00 IE 4 ©
                    <URL:http://www.jibbering.c om/faq/> JL/RC: FAQ of news:comp.lang. javascript
                    <URL:http://www.merlyn.demo n.co.uk/js-index.htm> jscr maths, dates, sources.
                    <URL:http://www.merlyn.demo n.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.

                    Comment

                    • Michael Winter

                      #11
                      Re: Changing strings to numbers(easy... maybe)

                      Dr John Stockton wrote:

                      [snip]
                      [color=blue]
                      > Michael : Matches to /^-\d+$/ are integers too.[/color]

                      Yes. It would be acceptable to prefix the number with a plus, too.

                      Perhaps I should have named the function, isPositiveDecim alInteger,
                      but that seems a little excessive. :)

                      [snip]

                      Mike

                      --
                      Michael Winter
                      Replace ".invalid" with ".uk" to reply by e-mail.

                      Comment

                      • Dr John Stockton

                        #12
                        Re: Changing strings to numbers(easy... maybe)

                        JRS: In article <1109635202.504 974.197080@f14g 2000cwb.googleg roups.com>
                        , dated Mon, 28 Feb 2005 16:00:02, seen in news:comp.lang. javascript,
                        mike <hillmw@charter .net> posted :[color=blue]
                        >Or this !!
                        >
                        >sum = (a-0) + (b-0) + (c-0);[/color]

                        Even sum = -(-a-b-c) is better than that (and is fairly short).

                        --
                        © John Stockton, Surrey, UK. ?@merlyn.demon. co.uk Turnpike v4.00 IE 4 ©
                        <URL:http://www.jibbering.c om/faq/> JL/RC: FAQ of news:comp.lang. javascript
                        <URL:http://www.merlyn.demo n.co.uk/js-index.htm> jscr maths, dates, sources.
                        <URL:http://www.merlyn.demo n.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.

                        Comment

                        Working...