Limit number to ####.## format

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

    Limit number to ####.## format

    How do I ensure a number has no more than 4 digits and 2 decimal places
    (adds .0 or .00 as necessary) onblur using reg expressions? Hints or
    solutions appreciated.

    John


  • Michael Winter

    #2
    Re: Limit number to ####.## format

    On Sun, 08 Aug 2004 23:37:39 GMT, johkar <nosendjunk@lin k.net> wrote:
    [color=blue]
    > How do I ensure a number has no more than 4 digits and 2 decimalplaces
    > (adds .0 or .00 as necessary) onblur using reg expressions?Hin ts or
    > solutions appreciated.[/color]

    This is partially answered in the group FAQ (it's a good idea to read it
    before posting). See <URL:http://jibbering.com/faq/#FAQ4_6>. The code
    there add a function to Number objects, called toFixed. You call it with
    the number of decimal places you want and it returns a formatted string.
    For example:

    var num = 5.673;
    var str = num.toFixed(2); // Contains '5.67'

    If the number is an integer, the returned string will have two zeros (0).

    Once you've converted the number to the correct decimal format, you can
    use the regular expression below to check for the correct overall format:

    /^[0-9]{1,4}\.[0-9]{2}$/

    For example (continued from above):

    if(/[0-9]{1,4}\.[0-9]{2}/.test(str)) {
    // Is of the format ####.##
    } else {
    // Number has five or more digits in the integer portion
    }

    As the decimal portion will always pass, I suppose you could use

    /^[0-9]{1,4}\./

    instead. The latter regular expression will probably be quicker (not by
    much), though the former will be self-documenting.

    Hope that helps,
    Mike

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

    Comment

    • johkar

      #3
      Re: Limit number to ####.## format

      Thanks, I appreciate your help and the friendly reminder to check the FAQs
      first.

      John

      "Michael Winter" <M.Winter@bluey onder.co.invali d> wrote in message
      news:opscfuoqdb x13kvk@atlantis ...[color=blue]
      > On Sun, 08 Aug 2004 23:37:39 GMT, johkar <nosendjunk@lin k.net> wrote:
      >[color=green]
      > > How do I ensure a number has no more than 4 digits and 2 decimalplaces
      > > (adds .0 or .00 as necessary) onblur using reg expressions?Hin ts or
      > > solutions appreciated.[/color]
      >
      > This is partially answered in the group FAQ (it's a good idea to read it
      > before posting). See <URL:http://jibbering.com/faq/#FAQ4_6>. The code
      > there add a function to Number objects, called toFixed. You call it with
      > the number of decimal places you want and it returns a formatted string.
      > For example:
      >
      > var num = 5.673;
      > var str = num.toFixed(2); // Contains '5.67'
      >
      > If the number is an integer, the returned string will have two zeros (0).
      >
      > Once you've converted the number to the correct decimal format, you can
      > use the regular expression below to check for the correct overall format:
      >
      > /^[0-9]{1,4}\.[0-9]{2}$/
      >
      > For example (continued from above):
      >
      > if(/[0-9]{1,4}\.[0-9]{2}/.test(str)) {
      > // Is of the format ####.##
      > } else {
      > // Number has five or more digits in the integer portion
      > }
      >
      > As the decimal portion will always pass, I suppose you could use
      >
      > /^[0-9]{1,4}\./
      >
      > instead. The latter regular expression will probably be quicker (not by
      > much), though the former will be self-documenting.
      >
      > Hope that helps,
      > Mike
      >
      > --
      > Michael Winter
      > Replace ".invalid" with ".uk" to reply by e-mail[/color]


      Comment

      • Dr John Stockton

        #4
        Re: Limit number to ####.## format

        JRS: In article <7PyRc.13780$cK .7866@newsread2 .news.pas.earth link.net>,
        dated Sun, 8 Aug 2004 23:37:39, seen in news:comp.lang. javascript,
        johkar <nosendjunk@lin k.net> posted :[color=blue]
        >How do I ensure a number has no more than 4 digits and 2 decimal places
        >(adds .0 or .00 as necessary) onblur using reg expressions? Hints or
        >solutions appreciated.[/color]

        In javascript, a number is stored as an IEEE Double, a floating-point
        binary quantity. Your description is only meaningful when applied to a
        string of characters intended to represent a number.

        Decimal places are digits too; but I suppose you mean to hope for such
        as '1234.56' and accept '1234.5' and '1234'. '1234.' ought not to be
        allowed; it is a deprecated form. You should likewise require at least
        one digit before the dot.

        This, lightly tested, should check for validity :-
        S = F.X2.value
        OK = /^\d{1,4}(\.\d\d ?)?$/.test(S)

        FAQ section 4.6 (and my js-round.htm) refers to the conversion from type
        Number to type String; not really applicable here. The following,
        lightly tested, will sort out the decimal places :-
        if (OK) S = S.replace(/(\.\d)$/, "$10").repl ace(/^(\d+)$/, "$1.00")

        In it, $1 refers to what the parenthesised bit found. The line may not
        be optimum; but it does avoid going via a Number for what is logically a
        String operation.

        See my js-valid.htm.


        Before responding, please read section 2.3 of the newsgroup FAQ until
        you understand it all. Especially paragraph 6.

        --
        © John Stockton, Surrey, UK. ?@merlyn.demon. co.uk Turnpike v4.00 IE 4 ©
        <URL:http://jibbering.com/faq/> JL / RC : FAQ for 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

        • Matt Kruse

          #5
          Re: Limit number to ####.## format

          Michael Winter wrote:[color=blue][color=green]
          >> How do I ensure a number has no more than 4 digits and 2
          >> decimalplaces (adds .0 or .00 as necessary) onblur using reg
          >> expressions?Hin ts or solutions appreciated.[/color]
          > This is partially answered in the group FAQ (it's a good idea to read
          > it before posting). See <URL:http://jibbering.com/faq/#FAQ4_6>. The
          > code there add a function to Number objects, called toFixed.[/color]

          IMO, someone should take the time to write printf() and sprintf() functions
          which behave in the 'standard' way. That would be really handy in js, and
          instantly useable by most people with a programming background.
          Any volunteers? ;)

          --
          Matt Kruse



          Comment

          • Dr John Stockton

            #6
            Re: Limit number to ####.## format

            JRS: In article <cf8j6n0hi1@new s2.newsguy.com> , dated Mon, 9 Aug 2004
            14:27:16, seen in news:comp.lang. javascript, Matt Kruse
            <newsgroups@mat tkruse.com> posted :[color=blue]
            >Michael Winter wrote:[color=green][color=darkred]
            >>> How do I ensure a number has no more than 4 digits and 2
            >>> decimalplaces (adds .0 or .00 as necessary) onblur using reg
            >>> expressions?Hin ts or solutions appreciated.[/color]
            >> This is partially answered in the group FAQ (it's a good idea to read
            >> it before posting). See <URL:http://jibbering.com/faq/#FAQ4_6>. The
            >> code there add a function to Number objects, called toFixed.[/color]
            >
            >IMO, someone should take the time to write printf() and sprintf() functions
            >which behave in the 'standard' way. That would be really handy in js, and
            >instantly useable by most people with a programming background.
            >Any volunteers? ;)[/color]

            I've been programming for a number of years, and AFAIR I have never used
            a language with printf() or sprintf(). That casts some slight doubt on
            your argument, and renders it impossible for me to code such functions
            without access to a full and authoritative specification.

            However, AISB, highly flexible functions need for implementation a
            considerable amount of code (especially in a language which is not
            ideally suited to efficient manipulation of string internals), and on a
            given Web page or Web site only a small proportion of the flexibility
            will usually be used.

            In other words, it would be bloatware.

            What can reasonably be put into a compiler's library, especially with
            smart linking, is quite inappropriate in a scripting language for pages
            which are likely to be distributed over slow links - into the boonies,
            over the air, etc.


            Via the FAQ and by other means one can find a large number of solutions
            to the task of rounding a javascript Number to a string with N or 2
            decimal places, some of which also format the integer part.

            It might be worth examining the allied but distinct question of
            "normalisin g" a String that represents a number, without converting
            it to Number - for example converting '123.456' to '+000123.45' or to
            ' +123.45' or ... .

            The necessary parameters seem to be places before the point, places
            after, leading zeroes or spaces or not, sign or not.

            For simplicity, one would either prohibit excess decimals or specify
            truncation towards zero - numeric input strings should be validated
            first, to deal with unreasonable input.

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

            • Matt Kruse

              #7
              Re: Limit number to ####.## format

              Dr John Stockton wrote:[color=blue]
              > I've been programming for a number of years, and AFAIR I have never
              > used a language with printf() or sprintf().[/color]

              C/C++/Perl - pretty common languages, especially among people writing
              Javascript.

              Delphi, Pascal, and VBScript are not languages used by most experienced
              programmers ;)

              --
              Matt Kruse



              Comment

              • Evertjan.

                #8
                Re: Limit number to ####.## format

                Matt Kruse wrote on 10 aug 2004 in comp.lang.javas cript:[color=blue]
                > Dr John Stockton wrote:[color=green]
                >> I've been programming for a number of years, and AFAIR I have never
                >> used a language with printf() or sprintf().[/color]
                >
                > C/C++/Perl - pretty common languages, especially among people writing
                > Javascript.[/color]

                Have you any scientific evidence [from systematic investigation] for this
                claim ? I would hypothese most javascript programmers nowadays don't know
                thes languages from s.., at all.
                [color=blue]
                > Delphi, Pascal, and VBScript are not languages used by most experienced
                > programmers ;)[/color]

                Again I doubt your wisdom. The subjectivenesse s of "experience d
                programmers" and the "most" ["most programmers with experience" or
                programmerds with the most experience"?] are only partly softened by the
                smily.

                --
                Evertjan.
                The Netherlands.
                (Please change the x'es to dots in my emailaddress)

                Comment

                • Dr John Stockton

                  #9
                  Re: Limit number to ####.## format

                  JRS: In article <cfbago02sh2@ne ws2.newsguy.com >, dated Tue, 10 Aug 2004
                  15:17:25, seen in news:comp.lang. javascript, Matt Kruse
                  <newsgroups@mat tkruse.com> posted :[color=blue]
                  >Dr John Stockton wrote:[color=green]
                  >> I've been programming for a number of years, and AFAIR I have never
                  >> used a language with printf() or sprintf().[/color]
                  >
                  >C/C++/Perl - pretty common languages, especially among people writing
                  >Javascript.
                  >
                  >Delphi, Pascal, and VBScript are not languages used by most experienced
                  >programmers ;)[/color]

                  Agreed, of course; it explains the poor quality of so much software.
                  Experience can generate wisdom, but generally does not.

                  --
                  © John Stockton, Surrey, UK. ?@merlyn.demon. co.uk Turnpike v4.00 MIME. ©
                  <URL:http://www.merlyn.demo n.co.uk/> TP/BP/Delphi/&c., FAQqy topics & links;
                  <URL:http://www.merlyn.demo n.co.uk/clpb-faq.txt> RAH Prins : c.l.p.b mFAQ;
                  <URL:ftp://garbo.uwasa.fi/pc/link/tsfaqp.zip> Timo Salmi's Turbo Pascal FAQ.

                  Comment

                  Working...