isInteger, isFloat functions?

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

    #16
    Re: isInteger, isFloat functions?

    On 20/9/04 2:00 pm, Fred Oz wrote:
    [color=blue]
    > Philip Ronan wrote:
    >
    >[color=green]
    >> Really?
    >> javascript:aler t(1/0) returns "Inf" in IE.
    >>[/color]
    >
    > And now IE is an authority on mathematics? Heaven forbid![/color]

    OK then, how about the ECMA-262 specification:[color=blue][color=green]
    >> Division of a non-zero finite value by a zero results in a signed
    >> infinity.[/color][/color]


    --
    Philip Ronan
    phil.ronanzzz@v irgin.net
    (Please remove the "z"s if replying by email)


    Comment

    • Andrew Thompson

      #17
      Re: isInteger, isFloat functions?

      On 20 Sep 2004 13:23:12 GMT, Evertjan. wrote:
      [color=blue][color=green]
      >> javascript:aler t(1/0) -> 'Infinity'
      >> javascript:aler t(0/0) -> 'NaN'
      >> javascript:aler t(-1/0) -> '-Infinity'
      >>
      >> Makes perfect sense to me.[/color][/color]
      ....[color=blue]
      > And which of them are integers ?[/color]

      <please insert 'mathematician' now>
      .....
      </please insert 'mathematician' now>

      Comment

      • Michael Winter

        #18
        Re: isInteger, isFloat functions?

        On Mon, 20 Sep 2004 21:12:54 +1000, Fred Oz <ozfred@iinet.n et.auau> wrote:

        [snip]
        [color=blue]
        > Testing strings using regular expressions to see if they have
        > decimal places (and how many), surplus characters, scientific
        > notation, etc. requires exhaustive testing [...][/color]

        Not at all:

        /^(0|[1-9])\d*$/

        ensures that the string contains an integer with no leading zeros.

        /^(-|+)?(0|[1-9])\d*$/

        allows for signed integers.

        To check for basic real numbers, it can be modified to:

        /^(0|[1-9])\d*(\.\d+)?$/

        which allows integer or real number inputs. To force decimal places and to
        limit their number again, only simple modification is necessary:

        /^(0|[1-9])\d*\.\d+$/ // must be real
        /^(0|[1-9])\d*\.\d\d$/ // must be real with two decimal places
        /^(0|[1-9])\d*\.\d{1,5}$/ // must be real with at most five d.p.

        Scientific notation:

        /^(0|[1-9])\d*\.\d+e(-|+)?\d+$/i

        Optional scientific notation:

        /^(0|[1-9])\d*\.\d+(e(-|+)?\d+)?$/i

        Optional scientific notation with positive and negative numbers:

        /^(-|+)?(0|[1-9])\d*\.\d+(e(-|+)?\d+)?$/i

        Mandatory canonical scientific notation:

        /^(-|+)?[1-9]\.\d+e(-|+)?[1-9]\d*$/i

        Hexadecimal:

        /^0x[0-9a-f]+$/i

        [Note: these are untested]

        The problem with using parseInt and parseFloat is that parsing stops at an
        unrecognised character. That doesn't really tell you if the value's format
        is correct or not, just that part of it converts to a number. If you want
        check an input format, regular expressions are the best approach.

        As you can see from the above, it doesn't take much effort once you've
        established some basic patterns. After that point, it's simply a matter of
        adding the components in the appropriate places.
        [color=blue]
        > How about:
        >
        > var x = someValue;
        > if (x == parseInt(x) && x == parseFloat(x)) {[/color]

        Calling parseInt without a radix argument can be unpredictable. Don't do
        it.

        [snip]

        Mike

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

        Comment

        • Dr John Stockton

          #19
          Re: isInteger, isFloat functions?

          JRS: In article <ec027e73.04091 91810.55afc562@ posting.google. com>,
          dated Sun, 19 Sep 2004 19:10:21, seen in news:comp.lang. javascript, D.
          Alvarado <laredotornado@ gmail.com> posted :
          [color=blue]
          > Does anyone have handy functions for testing whether a text field value is
          >
          >a) a valid integer
          >b) a valid floating point number?[/color]

          At least for the first case, the test might or might not need to
          include/exclude a sign and/or zero itself.

          Floating-point numbers are of the form +12.345E-6 ; you may instead
          want to accept only fixed-point <digits> optional: <point><digit s> .

          See <URL:http://www.merlyn.demo n.co.uk/js-valid.htm>.

          Normally, one can limit the number of digits in an integer of fixed-
          point number.

          --
          © John Stockton, Surrey, UK. ?@merlyn.demon. co.uk Turnpike v4.00 MIME. ©
          Web <URL:http://www.merlyn.demo n.co.uk/> - w. FAQish topics, links, acronyms
          PAS EXE etc : <URL:http://www.merlyn.demo n.co.uk/programs/> - see 00index.htm
          Dates - miscdate.htm moredate.htm js-dates.htm pas-time.htm critdate.htm etc.

          Comment

          • Dr John Stockton

            #20
            Re: isInteger, isFloat functions?

            JRS: In article <cilrvf$u98$1@n ews.datasync.co m>, dated Mon, 20 Sep
            2004 01:05:33, seen in news:comp.lang. javascript, Fox
            <fox@fxmahoney. com> posted :[color=blue]
            >D. Alvarado wrote:[/color]
            [color=blue][color=green]
            >> Does anyone have handy functions for testing whether a text field value is
            >>
            >> a) a valid integer[/color]
            >
            >function
            >isInteger(s)
            >{
            > var n = trim(s);
            > return n.length > 0 && !(/[^0-9]/).test(n);[/color]

            return /^\d+$/.test(n) // seems simpler
            return /^[+-]?\d+$/.test(n) // seems better
            [color=blue]
            >}
            >[color=green]
            >> b) a valid floating point number?[/color]
            >
            >function
            >isFloat(s)
            >{
            > var n = trim(s);
            > return n.length>0 && !(/[^0-9.]/).test(n) && (/\.\d/).test(n);[/color]

            return /^[+-]?\d+(\.\d+)?$/.test(n) // seems better
            // but the function deals with fixed-, not floating-, point.
            [color=blue]
            >}
            >
            >
            >isFloat "qualifies" and differentiates from an integer by testing for a decimal
            >point and at least one digit after it. Therefore, 123. will not qualify as a
            >floating point number [nor an integer in isInteger] -- it is an invalid input.
            >If you require a digit *before* the decimal point for a float, you'll have to
            >adjust the regex.[/color]

            That should be done, if circumstances permit; international
            recommendations deprecate a decimal point that it not surrounded by
            digits.

            --
            © 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

            • Lee

              #21
              Re: isInteger, isFloat functions?

              Philip Ronan said:[color=blue]
              >
              >On 20/9/04 12:44 pm, Fred Oz wrote:
              >[color=green]
              >> Philip Ronan wrote:
              >>
              >>[color=darkred]
              >>> It will also fail when t = infinity (e.g., "t=1/0")
              >>>[/color]
              >>
              >> 1/0 is not infinity, is it "undefined"- as is the result
              >> of any division by zero.
              >>
              >> Cheers, Fred.[/color]
              >
              >Really?
              >javascript:ale rt(1/0) returns "Inf" in IE.[/color]

              Really.
              Division by zero is no more a mathematical operation than is cracking an egg.
              Any numeric value assigned to it is simply a convenient fiction.

              Comment

              • Philip Ronan

                #22
                Re: isInteger, isFloat functions?

                On 20/9/04 7:07 pm, Lee wrote:
                [color=blue]
                > Really.
                > Division by zero is no more a mathematical operation than is cracking an egg.
                > Any numeric value assigned to it is simply a convenient fiction.[/color]

                So what? For the purposes of Javascript, 1/0=infinity. I only gave that as
                an example. If you want a better one, then how about a string of 500 "9"s.

                We are discussing JAVASCRIPT here, right?

                --
                Philip Ronan
                phil.ronanzzz@v irgin.net
                (Please remove the "z"s if replying by email)


                Comment

                • Fred Oz

                  #23
                  Re: isInteger, isFloat functions?

                  Philip Ronan wrote:

                  [color=blue]
                  > We are discussing JAVASCRIPT here, right?
                  >[/color]

                  Yes. And like all good programmers, if there is *any* chance
                  that your algorithm may result in division by zero, you
                  absolutely must test for it and avoid it.

                  As Andrew pointed out, 3 browsers gave 3 different (likely fully
                  ECMA-262 compliant) results. So if you don't test for division
                  by zero in the first place, you had better have done it afterward
                  because now you must deal with a bigger problem - infinity!

                  Fred.

                  Comment

                  • Lasse Reichstein Nielsen

                    #24
                    Re: isInteger, isFloat functions?

                    Fred Oz <ozfred@iinet.n et.auau> writes:
                    [color=blue]
                    > 1/0 is not infinity, is it "undefined"- as is the result
                    > of any division by zero.[/color]

                    "1/0" is "Infinity" when "1" and "0" and "/" are as defined by the
                    IEEE-754 standard. And "Infinity" is not the same as "undefined" when
                    thay are as defined by the ECMA-262 standard (ECMAScript).

                    /L 'and 1/-0 == -Infinity, even though 0 == -0 ... just don't think about it:)'
                    --
                    Lasse Reichstein Nielsen - lrn@hotpop.com
                    DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleD OM.html>
                    'Faith without judgement merely degrades the spirit divine.'

                    Comment

                    • Lasse Reichstein Nielsen

                      #25
                      Re: isInteger, isFloat functions?

                      "Evertjan." <exjxw.hannivoo rt@interxnl.net > writes:
                      [color=blue]
                      > I don't think infinity is an integer but I wouldn't mind if it is.[/color]

                      It is a number in Javascript. Whether it is an integer, I won't
                      begin to think about. Hmm. Math.floor(Infi nity) == Infinity
                      Nah.
                      [color=blue]
                      > (+t+1)!=+t ?[/color]

                      You don't need infinity for that in IEEE-754 floating point numbers.
                      As soon as the numbers becomes so large, that the precission is less
                      than 1, then t+1 cannot be represented and the result is the same as
                      t.

                      Example:
                      ---
                      var t = Math.pow(2,53);
                      if (t+1 == t) { alert("surprice "); }
                      ---

                      /L
                      --
                      Lasse Reichstein Nielsen - lrn@hotpop.com
                      DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleD OM.html>
                      'Faith without judgement merely degrades the spirit divine.'

                      Comment

                      • Evertjan.

                        #26
                        Re: isInteger, isFloat functions?

                        Lasse Reichstein Nielsen wrote on 20 sep 2004 in comp.lang.javas cript:[color=blue]
                        > var t = Math.pow(2,53);
                        > if (t+1 == t) { alert("surprice "); }[/color]

                        I cannot resist bettering you on that, Lasse:

                        alert("surprise ;-}")

                        --
                        Evertjan.
                        The Netherlands.
                        (Please change the x'es to dots in my emailaddress,
                        but let us keep the discussions in the newsgroup)

                        Comment

                        • Lasse Reichstein Nielsen

                          #27
                          Re: isInteger, isFloat functions?

                          "Evertjan." <exjxw.hannivoo rt@interxnl.net > writes:
                          [color=blue]
                          > I cannot resist bettering you on that, Lasse:
                          >
                          > alert("surprise ;-}")[/color]

                          I'll learn it eventually. Maybe. :)
                          /L
                          --
                          Lasse Reichstein Nielsen - lrn@hotpop.com
                          DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleD OM.html>
                          'Faith without judgement merely degrades the spirit divine.'

                          Comment

                          • Dr John Stockton

                            #28
                            Re: isInteger, isFloat functions?

                            JRS: In article <Xns956A7CBC393 5Aeejj99@194.10 9.133.29>, dated Mon, 20
                            Sep 2004 10:15:21, seen in news:comp.lang. javascript, Evertjan.
                            <exjxw.hannivoo rt@interxnl.net > posted :
                            [color=blue]
                            >t = "1.2e+33"
                            >alert(!/\./.test(+t) && +t==t)
                            >
                            >Though technically incorrect [John?],
                            >are such big/small numbers important to the OP ?[/color]

                            I think all such tests ate liable to fail with long numbers.
                            Long != big.
                            Also 125.1 fails, 125.0 passes.
                            IMHO, the method is basically unpredictable.

                            --
                            © 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

                            • Dr John Stockton

                              #29
                              Re: isInteger, isFloat functions?

                              JRS: In article <ec027e73.04091 91810.55afc562@ posting.google. com>,
                              dated Sun, 19 Sep 2004 19:10:21, seen in news:comp.lang. javascript, D.
                              Alvarado <laredotornado@ gmail.com> posted :[color=blue]
                              >Hello,
                              > Does anyone have handy functions for testing whether a text field value is
                              >
                              >a) a valid integer
                              >b) a valid floating point number?[/color]

                              Additionally :

                              You specify a text field, which is a string. Any response article which
                              does not start with a string has missed the point.

                              12345 is an integer string
                              12345.6 is a fixed-point string
                              12345.0 is a fixed-point string with an integer value
                              123.4e5 is a floating-point string with an integer value.

                              Before trying to get the answer right, it is necessary to get the
                              question right.

                              --
                              © John Stockton, Surrey, UK. ?@merlyn.demon. co.uk DOS 3.3, 6.20; Win98. ©
                              Web <URL:http://www.merlyn.demo n.co.uk/> - FAQqish topics, acronyms & links.
                              PAS EXE TXT ZIP via <URL:http://www.merlyn.demo n.co.uk/programs/00index.htm>
                              My DOS <URL:http://www.merlyn.demo n.co.uk/batfiles.htm> - also batprogs.htm.

                              Comment

                              • Philip Ronan

                                #30
                                Re: isInteger, isFloat functions?

                                On 20/9/04 9:29 pm, Fred Oz wrote:
                                [color=blue]
                                > Philip Ronan wrote:
                                >
                                >[color=green]
                                >> We are discussing JAVASCRIPT here, right?
                                >>[/color]
                                >
                                > Yes. And like all good programmers, if there is *any* chance
                                > that your algorithm may result in division by zero, you
                                > absolutely must test for it and avoid it.
                                >
                                > As Andrew pointed out, 3 browsers gave 3 different (likely fully
                                > ECMA-262 compliant) results. So if you don't test for division
                                > by zero in the first place, you had better have done it afterward
                                > because now you must deal with a bigger problem - infinity!
                                >
                                > Fred.[/color]

                                Sorry, I shouldn't have mentioned division by zero in the first place.

                                What I meant to refer to is the Javascript (ECMA-262) entity called
                                "Infinity". Any number greater than (roughly?) 10^308 equates to "Infinity"
                                in Javascript.

                                Let's get back to the original question:

                                If I entered this into a text box:
                                "9999999---99999.9" (replace "---" with 300 "9"s)
                                then it would fail this test for integers:
                                alert(!/\./.test(+t) && +t==t)

                                OK now?

                                --
                                Philip Ronan
                                phil.ronanzzz@v irgin.net
                                (Please remove the "z"s if replying by email)


                                Comment

                                Working...