Announcement

Collapse
No announcement yet.

Type Conversions _newbie

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

  • Type Conversions _newbie

    After 6 weeks of experimenting with PB, after 12 years VB, I decided it was time to bite the bullet and do a live project in PB9 rather than VB.
    All the Database stuff works fine but I come unstuck on the most simple bits of code, which in VB I never even had to to think about.
    In the code below I read a text field from MSAccess into sComment (code not shown)
    I then need to manipulate this string variable and extract two double variables from the manipulated text field.
    In the time I've spent on trying to do this, I would probably have completed the complete project in VB or VBA.

    Please don't take this as a shot at PB, rather, it's the sheltered life us VB converts come from. So please someone take the 5 seconds it needs to sort me out. Code snip follows. Fails on dLeft=CDBL(LEFT$(sComment,ip-1))
    (Not sure about dRight, didn't get that far)
    TIA
    ~~~
    #COMPILE EXE
    #DIM ALL

    FUNCTION PBMAIN () AS LONG
    DIM sComment AS STRING
    DIM iP AS INTEGER
    DIM dLeft AS DOUBLE
    DIM dRight AS DOUBLE
    sComment = "180 x 100cm"
    REPLACE " " WITH "" IN sComment
    REPLACE "cm" WITH "" IN sComment
    ip=INSTR(sComment,"x")
    MSGBOX STR$(ip)
    dLeft=CDBL(LEFT$(sComment,ip-1))
    MSGBOX STR$(dLeft)
    dRight=(CDBL(MID$(sComment,ip+1, LEN(sComment)-ip)
    END FUNCTION

  • #2
    IIRC, VB does automatic type conversion between numerics and strings. So all you need to do is use VAL:

    Code:
    CDBL( [B]VAL[/B](LEFT$(sComment,ip-1)) )
    I didn't compile the code, but it should be ok if you add the two VALs.
    kgpsoftware.com | Slam DBMS | PrpT Control | Other Downloads | Contact Me

    Comment


    • #3
      Hi Ian--
      This is probably the simplest modification to your code, just for info...
      Code:
      Function PBMain () AS LONG
        DIM sComment AS STRING
        DIM iP AS INTEGER
        DIM dLeft AS DOUBLE
        DIM dRight AS DOUBLE
      
        sComment = "180 x 100cm"
        ip=INSTR(sComment,"x")
        dLeft=VAL(sComment)
        dRight=VAL(Mid$(sComment,ip+1))
      End Function
      There's no need to remove spaces nor text characters like "cm", as the VAL() function automatically skips leading white space and stops scanning as soon as it finds a non-numeric character.

      There's no need to use CDBL() as PowerBASIC automatically selects the correct internal format for the assignment to a Double Float.

      Best regards,

      Bob Zale
      PowerBASIC Inc.

      Comment


      • #4
        There's no need to remove spaces nor text characters like "cm", as the VAL() function automatically skips leading white space and stops scanning as soon as it finds a non-numeric character
        I think it better technique to extract the 'characters of interest' rather than rely on the way VAL works (and yes it does work like that).


        Code:
        dLeft = VAL (LEFT$(sComment,ip-1))   ' get value of first number
        Not that I would expect the VAL() function to change behavior, but doing it "the long way" (above) will work forever regardless, and is IMO more self-documenting when you go back to that code six months after the last time you worked on it.

        So I guess that makes for two (2) opinions.

        MCM
        Michael Mattias
        Tal Systems (retired)
        Port Washington WI USA
        [email protected]
        http://www.talsystems.com

        Comment


        • #5
          Let's see now, on a weekend (not normal business hours almost anywhere in the world), a fella in New Zealand, new to the PB Community, posts a question about PB.

          Within minutes (well, 74 actually), he gets an (one) answer from the United Kingdom.

          60 minutes later he get a full explanation of his query from the tropical East Coast of the USA. And from the owner of the company, no less, who is the world's foremost knowledge expert on PB.

          And A few hours later he gets a *another* response from deep in the frozen wilds of of the middle of the USA from another world's foremost knowledge expert in PB, "improving/expanding" on the tropical explanation.

          Asia is expected to pop in soon.

          Ain't the PB Forums just grand?

          ==================================================
          "It is unbecoming for young men to utter maxims."
          Aristotle (384-322 B.C.)
          ==================================================
          It's a pretty day. I hope you enjoy it.

          Gösta

          JWAM: (Quit Smoking): http://www.SwedesDock.com/smoking
          LDN - A Miracle Drug: http://www.SwedesDock.com/LDN/

          Comment


          • #6
            Originally posted by Gösta H. Lovgren-2 View Post
            And A few hours later he gets a *another* response ...from another world's foremost knowledge expert in PB
            MCM can be idiosyncratic, bur extraterrestrial? Surely not.

            Comment


            • #7
              Gösta's post sums it up beautifully.
              I climbed into the shower this morning and planned my day (as you do!), figuring to restart the project in good old safe VB, with an intention of coming back and doing a conversion to PB after the event (with a vague feeling that this would never happen)
              The nature and timeliness of the responses I read after the shower fired me up, and I'm back into my first live PB project.
              Thank you all.

              Ian B

              Comment


              • #8
                Originally posted by Chris Holbrook View Post
                MCM can be idiosyncratic, bur extraterrestrial? Surely not.
                Are you sure?

                =============================
                "My people are destroyed
                for lack of knowledge.....!"
                Hosea 46
                =============================
                It's a pretty day. I hope you enjoy it.

                Gösta

                JWAM: (Quit Smoking): http://www.SwedesDock.com/smoking
                LDN - A Miracle Drug: http://www.SwedesDock.com/LDN/

                Comment


                • #9
                  I tend to lean towards MCM's way of extracting the characters of interest over Bob's comment of
                  There's no need to remove spaces nor text characters like "cm", as the VAL() function automatically skips leading white space and stops scanning as soon as it finds a non-numeric character.
                  Only because in this case that is true, but even the sample in the help file uses a dollar value and shows getting rid of the $ first.

                  In both cases the answer is correct, but for newbies, or just those of us not thinking and miss the lil difference, may miss this point and struggle as to why the code does not work correctly (when in fact it is working as advertised)

                  Bob's comment of
                  PowerBASIC automatically selects the correct internal format for the assignment to a Double Float.
                  Where is that declared that its a Double Float? (I could not find it in the docs, unless its implied maybe in an example such as "i& = VAL("10.101e3") ' 10101 ~ 10.101*(10^3)"

                  Is there a section I am not seeing in the docs that tells me what datatype is returned from a PB keyword? It would be nice to know (especially when debugging a troublesome problem such as I am now that I can not figure out if its a datatype problem or something else I should be looking for)
                  Engineer's Motto: If it aint broke take it apart and fix it

                  "If at 1st you don't succeed... call it version 1.0"

                  "Half of Programming is coding"....."The other 90% is DEBUGGING"

                  "Document my code????" .... "WHYYY??? do you think they call it CODE? "

                  Comment


                  • #10
                    Only because in this case that is true...
                    Let's be very careful to avoid giving misinformation to someone who is new to PowerBASIC. My description is true in every case, not just this one. The VAL() function always skips leading white space and always terminates on the first non-numeric character.

                    ...even the sample in the help file uses a dollar value and shows getting rid of the $ first
                    The PowerBASIC Help File is correct. That's because a "$" character is not leading white space. White space is skipped, not other characters.

                    Where is that declared that its a Double Float?
                    Actually, in the example code, you'll find that two variables are declared as DOUBLE:

                    DIM dLeft AS DOUBLE
                    DIM dRight AS DOUBLE

                    When you assign any numeric value to a PowerBASIC variable, it is always converted automatically to the appropriate internal format. It is never, ever necessary to force it using a function such as CDBL().

                    The value returned from any and every numeric function in PowerBASIC is automatically adjusted to the correct internal format depending upon its usage and context. If you assign the result of SIN() to an integer variable, you'll get an integer value, even if it may not be as meaningful as it could be as a floating point data type. With PowerBASIC, you never, ever have to give that any concern. It's always automatic and it's always as accurate as possible given the context.

                    The example I gave was the simplest possible to make it straightforward for a new PowerBASIC user. If anyone is more comfortable extracting non-numeric characters before calculating the values, that's fine. Just be prepared to accept that it's a direct duplication of the built-in run-time code, and will measureably slow the execution of your program. In my opinion, one should consider a limit to this sort of duplication of effort.

                    Best regards,

                    Bob Zale
                    PowerBASIC Inc.

                    Comment


                    • #11
                      Just be prepared to accept that it's a direct duplication of the built-in run-time code, and will measureably slow the execution of your program.
                      You must be running for office, using scare tactics like that.

                      But on the 'truth-o-meter' we'll give that a 'partly true', because altough the runtime is still doing the checks, if the programmer removes the non-numeric characters, the runtime ain't gotta do it, do it? And "measureable?" Well, maybe... if you are doing many such operations.

                      OTOH, if you vote for me you will have more understandable code. It takes a lot of runtime clocks to offset the extra programmer time you'll spend figuring out how/why the 'shortcut' works.

                      I heard something on the radio yesterday... the very first time I had ever heard it. I like it a lot, and think it applies to programming extremely well:

                      "There is no elevator to success; there are only stairs"

                      MCM
                      Michael Mattias
                      Tal Systems (retired)
                      Port Washington WI USA
                      [email protected]
                      http://www.talsystems.com

                      Comment


                      • #12
                        Ian, you've been shown how to make your code work, but not why it actually failed. The CDBL, along with all of the other convert functions, require a numeric expression, not a string expression. Probably, though, that's already become obvious to you in this thread.

                        Comment


                        • #13
                          But on the 'truth-o-meter'...
                          Better you stick to your "Veg-O-Matic" on this one, Michael. Removal of characters requires creation of an entirely new temporary string. That's at least 1000 times slower than simply "skipping" blank spaces and terminating on a non-numeric. That is not a partial truth.

                          You should also use a bit more care than describing this as a "shortcut". My example uses a common language feature in a documented fashion. If you want to duplicate code in your programs, that's fine with me. Of course, if we actually follow that logic we might code something like:

                          x$ = "Hello"
                          x$ = LEFT$(x$,5)

                          ... just to be certain no extra characters were added to x$ (not recommended).

                          Every programmer can (and should) make his own choice about this. But I wouldn't be doing my customers justice if I failed to point out all of the features of PowerBASIC functions. Use them in a way that serves you best.

                          Best regards,

                          Bob Zale
                          PowerBASIC Inc.

                          Comment


                          • #14
                            Originally posted by Michael Mattias View Post
                            "There is no elevator to success; there are only stairs"

                            MCM
                            Or in other words "I've had it hard and so should you. So there!"


                            =========================================
                            When someone does something good, applaud!
                            You will make two people happy.
                            Samuel Goldwyn
                            =========================================
                            It's a pretty day. I hope you enjoy it.

                            Gösta

                            JWAM: (Quit Smoking): http://www.SwedesDock.com/smoking
                            LDN - A Miracle Drug: http://www.SwedesDock.com/LDN/

                            Comment


                            • #15
                              Ms

                              Here's a snip similar to Bob's. but using the PB function REMAIN$. If I was working with a bunch of strings of the form: value x value, then I might assign "x" to a string or string equate to start with and use that.

                              Code:
                              #COMPILE EXE
                              #DIM ALL
                              
                              FUNCTION PBMAIN () AS LONG
                                  DIM sComment AS STRING
                                  DIM dLeft AS DOUBLE
                                  DIM dRight AS DOUBLE
                                  sComment = "180 x 100cm"
                                  dLeft   =  VAL(sComment)
                                  dRight  =  VAL(REMAIN$(sComment,"x"))
                                  ? FORMAT$(dLeft) +$CRLF + FORMAT$(dRight)
                              END FUNCTION
                              However if you are dealing with mixed string parsing, lets say for example:
                              500 pcs @ $0.01 each, then I could use a similar routine, but REMAIN$ would be coded to return after the "$" character.

                              Also, lets say you have a string with wd x ht x depth dimensions, then INSTR can be used to help as shown in the following:

                              Code:
                              #COMPILE EXE
                              #DIM ALL
                              
                              FUNCTION PBMAIN () AS LONG
                                  DIM sComment    AS STRING
                                  DIM firstX      AS LONG
                                  DIM dLeft       AS DOUBLE
                                  DIM dCenter     AS DOUBLE
                                  DIM dRight      AS DOUBLE
                                  sComment = "180 x 100 x 50cm"
                                  dLeft   =   VAL(sComment)
                                  firstX  =   INSTR(sComment,"x") + 1
                                  dCenter =   VAL(REMAIN$(sComment,"x"))
                                  dRight  =   VAL(REMAIN$(firstX,sComment,"x"))
                                  ? FORMAT$(dLeft) +$CRLF + FORMAT$(dCenter)+$CRLF + FORMAT$(dRight)
                              END FUNCTION
                              Bob's suggested code or the above both get the job done. Using REMAIN$ seems to run a wee bit faster in some testing I used.
                              Rick Angell

                              Comment


                              • #16
                                Let's be very careful to avoid giving misinformation to someone who is new to PowerBASIC. My description is true in every case, not just this one. The VAL() function always skips leading white space and always terminates on the first non-numeric character.
                                My apologize Bob, I did not mean to confuse, but more to demonstrate what is obviously in the Help file. Escpecially since I came from a VB background, and never really looked at just how keywords worked "Under the Hood" sort of thing

                                Now that I know, I endeavor to go back over some major parts of my code to eliminate the need to needlessly remove characters from my code twice, and not knowing I was doing it.

                                I was confused though about
                                Actually, in the example code, you'll find that two variables are declared as DOUBLE:

                                DIM dLeft AS DOUBLE
                                DIM dRight AS DOUBLE
                                I could not find that in the docs, but then I realized you meant from the example that Ian originally posted.

                                Just out of curiosity, could the examples in the help files be modified to show the declarations of the variables? (or is that something more suited for a new feature request?)
                                Engineer's Motto: If it aint broke take it apart and fix it

                                "If at 1st you don't succeed... call it version 1.0"

                                "Half of Programming is coding"....."The other 90% is DEBUGGING"

                                "Document my code????" .... "WHYYY??? do you think they call it CODE? "

                                Comment


                                • #17
                                  On that Veg-O-Matic thing...

                                  Not being privy to exactly how you handle the VAL() function, I had to 'make a guess'

                                  I made a guess that you check for leading leading white space and non-numeric characters, create a 'net' string and pass that to one of your library functions.. i.e., creating the same string the programmer is creating.

                                  Apparently you actually do everything "inline on the fly" with the string you are given.

                                  (Not documented. Nor would I expect it to be).

                                  Next time I hack into your libraries I'll make sure I get everything.

                                  MCM
                                  Michael Mattias
                                  Tal Systems (retired)
                                  Port Washington WI USA
                                  [email protected]
                                  http://www.talsystems.com

                                  Comment


                                  • #18
                                    Michael, VAL has been a BASIC command since the late 1970's. I first used it in programming with TRS-80 Level II BASIC. In MS versions of BASIC it has remained the same, but it been improved over time for special cases, I did not find on-line the TRS manual but in the GW-BASIC manual :
                                    Purpose: Returns the numerical value of string x$.
                                    Comments: The VAL function also strips leading blanks, tabs, and line feeds from the argument string. ...
                                    If the first character of x$ is not numeric, the VAL(x$) will return zero.
                                    http://www.antonis.de/qbebooks/gwbasman/val.html
                                    In MSDN for VB it says:
                                    [purpose:] Returns the numbers contained in a string as a numeric value of appropriate type.
                                    Remarks:
                                    The Val function stops reading the string at the first character it cannot recognize as part of a number. Symbols and characters that are often considered parts of numeric values, such as dollar signs and commas, are not recognized. However, the function recognizes the radix prefixes &O (for octal) and &H (for hexadecimal). Blanks, tabs, and linefeed characters are stripped from the argument.
                                    http://msdn.microsoft.com/en-us/library/k7beh1x9(VS.80).aspx
                                    And of course for PB...
                                    Purpose: Return the equivalent of a argument.
                                    Remarks: VAL turns a string argument into a number. If string_expression begins with numeric characters (0 to 9 and +, -, or.), but also contains non-numeric characters, VAL returns the number up to the point of the non-numeric character. If string_expression does not begin with a numeric character, VAL returns 0. The string argument should not contain any commas, as VAL terminates processing if a comma is encountered. Leading white-space characters (spaces, tabs, and linefeed characters) are ignored.
                                    ..

                                    VAL can also be used to convert string arguments that are in the form of Hexadecimal, Binary and Octal numbers. Hexadecimal values should be prefixed with "&H" and Binary with "&B". Octal values may be prefixed "&O", "&Q" or just "&". If string_expression contains a leading zero, the result is returned as an unsigned value; otherwise, a signed value is returned
                                    As noted, VAL has seen improvements since its beginnings to handle special cases, but the general functioning has not. This and the special cases are spelled out in PB's manual.
                                    Last edited by Richard Angell; 5 Oct 2008, 08:16 PM. Reason: link moved to correct quote portion
                                    Rick Angell

                                    Comment


                                    • #19
                                      Wow Rick did you ever bring me flashbacks of the 80s
                                      TRS-80 Level II BASIC
                                      Holy Trash-80 batman

                                      Imagine if we still had tape-decks for hard drives (or more like a floppy)

                                      Apparently the core idea of keywords (or more to the point their actual function) has been around longer than I thought, and maybe why taken as "This is how it works" rather than actually reading "This is how it works" sort of thing?
                                      Engineer's Motto: If it aint broke take it apart and fix it

                                      "If at 1st you don't succeed... call it version 1.0"

                                      "Half of Programming is coding"....."The other 90% is DEBUGGING"

                                      "Document my code????" .... "WHYYY??? do you think they call it CODE? "

                                      Comment


                                      • #20
                                        Imagine if we still had tape-decks for hard drives (or more like a floppy)
                                        Thanks but I'll pass on that exercise

                                        Many of PB's BASIC functions and statements can be traced a long way back and they still remain faithful to the roots. This feature is really helpful for those with a long history of programming in BASIC. In looking at the VAL function one can see that it was improved to do a bit more with respect to numbers presented as powers and in non-decimal bases such as binary,hex and octal. Every so often there has been a forum discussion on some function or statement with a long history like VAL has.

                                        Sometimes when one comes from only a background of some of the newer specialized BASICs they might not realize that the syntax they were learning was not mainstream BASIC at all but some hybrid put together an author without regard to keeping the faith with existing tried and true BASIC functions and statements. In fact sometimes BASIC syntax in these specialized offerings seems an afterthought and the author's C roots take over. Fortunately, you can quite normally rely on PB for updating old code to new compilers with minimal if any tweaking.
                                        Rick Angell

                                        Comment

                                        Working...
                                        X