Results 1 to 36 of 36

Thread: [RESOLVED] Having problems with this experiment code

  1. #1

    Thread Starter
    Lively Member
    Join Date
    Dec 2024
    Posts
    95

    Resolved [RESOLVED] Having problems with this experiment code

    I'm using Visual Studio 2022 on a Windows 10 desktop computer.

    I was trying to learn how to format an output string so that the string contain commas in the right places.

    The output string contains only numbers.

    I tried methods I found on here that did not work (See the commented out code at the bottom of the Sub).

    I finally got it to work flawlessly but now when I actually use the program and type in the number
    999999999999999999 the last few digits in the Messagebox are always wrong in the last three digits.

    I even tried using a textbox to hold the out put, and the same thing happens.

    Anyone have any ideas?

    Code:
    Private Sub Button7_Click(sender As Object, e As EventArgs) Handles Button7.Click
        'Dim myInteger As Int64
        Dim myInteger As ULong
        Dim myString As String
        myString = TextBox5.Text
       
    
        myInteger = Val(myString)
        If myInteger < 10 Then
            'MessageBox.Show(myInteger.ToString("0"))
    
        ElseIf myInteger < 100 Then
            MessageBox.Show(myInteger.ToString("00"))
            'TextBox6.Text = (myInteger.ToString("00")
        ElseIf myInteger < 1000 Then
            MessageBox.Show(myInteger.ToString("000"))
            'TextBox6.Text = (myInteger.ToString("000")
        ElseIf myInteger >= 1000 Then
            'MessageBox.Show(myInteger.ToString("0,000"))
            TextBox6.Text = (myInteger.ToString("0,000,000,000,000"))
        End If
    
        'myString = myInteger.ToString("n0")
        ''myInteger.ToString("N0")
        'TextBox5.Text = myInteger.ToString("n0")
        'Dim myInteger As Integer = 123456789
        'MessageBox.Show(myInteger.ToString("0,000,000"))
        'MessageBox.Show(myInteger.ToString("0,000"))
        'MessageBox.Show(myInteger.ToString("000"))
    End Sub

  2. #2
    PowerPoster PlausiblyDamp's Avatar
    Join Date
    Dec 2016
    Location
    Pontypool, Wales
    Posts
    2,836

    Re: Having problems with this experiment code

    When you say the output isn't correct, what are you expecting and what are you getting?

  3. #3

    Thread Starter
    Lively Member
    Join Date
    Dec 2024
    Posts
    95

    Re: Having problems with this experiment code

    When I type in 999999999999999999

    The result comes back as 1,000,000,000,000,000,128

  4. #4

    Thread Starter
    Lively Member
    Join Date
    Dec 2024
    Posts
    95

    Re: Having problems with this experiment code

    I'm off to try that now.....

  5. #5

    Thread Starter
    Lively Member
    Join Date
    Dec 2024
    Posts
    95

    Re: Having problems with this experiment code

    FordPerfect... it worked perfectly!

    Thank you much! Now all I have to do is count the characters in my input string and pass that to the code. Easy Peasy.

  6. #6
    Super Moderator dday9's Avatar
    Join Date
    Mar 2011
    Location
    South Louisiana
    Posts
    12,064

    Re: Having problems with this experiment code

    The problem you're having is probably due to a type conversion. myInteger (poorly named by the way) is defined as an unsigned long but the Val function returns a double. If you use the .NET specific function, ULong.TryParse instead, you would get the expected result.

    Here is a combination of TryParse with using FordPerfect's formatting suggestion:
    Code:
    Private Function FormatLargeNumber(value As String) As String
        Dim myLong As ULong
        If (Not ULong.TryParse(value, myLong)) Then
            Throw New Exception("Invalid unsigned long.")
        End If
        Return myLong.ToString("#,##0")
    End Function
    Fiddle: https://dotnetfiddle.net/wz2Ouu
    "Code is like humor. When you have to explain it, it is bad." - Cory House
    VbLessons | Code Tags | Sword of Fury - Jameram

  7. #7

    Thread Starter
    Lively Member
    Join Date
    Dec 2024
    Posts
    95

    Re: Having problems with this experiment code

    Quote Originally Posted by FordPrefect View Post
    Hi
    Yes, what he says!
    So far the code you gave me is working perfectly, and I've been trying to make it fail, and can't. I'll check out dday's
    suggestion as well!

  8. #8
    Super Moderator dday9's Avatar
    Join Date
    Mar 2011
    Location
    South Louisiana
    Posts
    12,064

    Re: Having problems with this experiment code

    By the way, you'll want to structure you code like how I showed you.

    From a design perspective you have all the logic crammed into the button's click event, which violates the single-responsibility principle. What if you wanted to do the same business logic somewhere else? Right now you'd need to manually set TextBox5's text, invoke the button's click, then get the text back from TextBox5.

    By setting up a function, that uses a String parameter and returns a String, you can use whatever String value you want and get the result in memory so that in turn you can use it wherever you want. For example, you'd replace the button's click event with:
    Code:
    ' changes to your existing code
    Private Sub Button7_Click(sender As Object, e As EventArgs) Handles Button7.Click
        Dim value As String = TextBox5.Text
        Dim formattedValue As String = FormatLargeNumber(value)
        TextBox5.Text = formattedValue
    End Sub
    
    ' illustrating that you can flexibly use this
    Private Sub ButtonSomewhereElse_Click(sender As Object, e As EventArgs) Handles ButtonSomewhereElse.Click
        Dim value As String = TextBoxSomewhereElse.Text
        Dim formattedValue As String = FormatLargeNumber(value)
        LabelSomewhereElse.Text = formattedValue
    End Sub
    "Code is like humor. When you have to explain it, it is bad." - Cory House
    VbLessons | Code Tags | Sword of Fury - Jameram

  9. #9

    Thread Starter
    Lively Member
    Join Date
    Dec 2024
    Posts
    95

    Re: Having problems with this experiment code

    dday9.... I like that!

    I've only been at this for a couple of months now, and will definitely take your advice and learn more about functions!

    Thank you so much!

  10. #10

    Thread Starter
    Lively Member
    Join Date
    Dec 2024
    Posts
    95

    Re: Having problems with this experiment code

    I finally got it to the point where I can start writing a Function to handle this.

    Code:
    Private Sub Button7_Click(sender As Object, e As EventArgs) Handles Button7.Click
        'Ford Prefect's original post...
        'Dim myInteger As Int64 = 999999999999999999
        'Dim myString As String = myInteger.ToString("#,##0")
        '-----------------------------------------------------
    
        'What I came up with...
        Dim myInteger As Int64 = 0
        myInteger = Convert.ToString(TextBox5.Text)
        Dim myString As String = myInteger.ToString("#,##0")
    
        TextBox5.Text = Convert.ToString(myInteger)
        TextBox6.Text = myString
    End Sub

  11. #11
    PowerPoster PlausiblyDamp's Avatar
    Join Date
    Dec 2016
    Location
    Pontypool, Wales
    Posts
    2,836

    Re: Having problems with this experiment code

    I don't think
    Code:
        myInteger = Convert.ToString(TextBox5.Text)
    is correct, that code is explicitly converting a string to a string, and then implicitly converting it to an Int64.

  12. #12

    Thread Starter
    Lively Member
    Join Date
    Dec 2024
    Posts
    95

    Re: Having problems with this experiment code

    Quote Originally Posted by PlausiblyDamp View Post
    I don't think
    Code:
        myInteger = Convert.ToString(TextBox5.Text)
    is correct, that code is explicitly converting a string to a string, and then implicitly converting it to an Int64.
    It works perfectly, though.

  13. #13
    PowerPoster
    Join Date
    Sep 2005
    Location
    Modesto, Ca.
    Posts
    5,353

    Re: Having problems with this experiment code

    Quote Originally Posted by Sonny McGhee View Post
    It works perfectly, though.
    No it doesn't. It only works because you've set Option Strict to Off (which you shouldn't unless absolutely necessary) and the compiler is correcting your mistake.

    Look at what your doing.

    TextBox5.Text is a String
    You then Convert the String to a String.
    Then you assign a String value to an Integer.

    Do you see the problem?

  14. #14

    Thread Starter
    Lively Member
    Join Date
    Dec 2024
    Posts
    95

    Re: Having problems with this experiment code

    Quote Originally Posted by wes4dbt View Post
    No it doesn't. It only works because you've set Option Strict to Off (which you shouldn't unless absolutely necessary) and the compiler is correcting your mistake.

    Look at what your doing.

    TextBox5.Text is a String
    You then Convert the String to a String.
    Then you assign a String value to an Integer.

    Do you see the problem?
    I have no idea what option strict is. So there's no way I could have set it to off.

  15. #15
    PowerPoster
    Join Date
    Sep 2005
    Location
    Modesto, Ca.
    Posts
    5,353

    Re: Having problems with this experiment code

    Your Visual Studio may have it default to Off. In the Solution Explorer Select MyProject, then Compile. You'll find it there.

    https://learn.microsoft.com/en-us/do...rict-statement

    Did you understand the explanation of what your doing wrong?

  16. #16

    Thread Starter
    Lively Member
    Join Date
    Dec 2024
    Posts
    95

    Re: Having problems with this experiment code

    Quote Originally Posted by wes4dbt View Post
    Your Visual Studio may have it default to Off. In the Solution Explorer Select MyProject, then Compile. You'll find it there.

    https://learn.microsoft.com/en-us/do...rict-statement

    Did you understand the explanation of what your doing wrong?
    Option strict is off and my code is running perfectly.

  17. #17
    PowerPoster PlausiblyDamp's Avatar
    Join Date
    Dec 2016
    Location
    Pontypool, Wales
    Posts
    2,836

    Re: Having problems with this experiment code

    Quote Originally Posted by Sonny McGhee View Post
    Option strict is off and my code is running perfectly.
    Option Strict being off doesn't mean your code is running perfectly, it simply means vb isn't warning you about potential problems.

    If you put something that isn't a number in the textbox then it isn't going to be perfect.

    Just because the right answer comes out doesn't mean the code is correct, using Convert.ToString on a string is a waste of time because a string is already a string and doesn't need converting.

  18. #18
    Super Moderator dday9's Avatar
    Join Date
    Mar 2011
    Location
    South Louisiana
    Posts
    12,064

    Re: Having problems with this experiment code

    I would recommend combining my code from post 7 and 10 along with PlausiblyDamp's suggestion of using Option Strict. I'd also wrap the method call in a Try/Catch:
    Code:
    Option Strict On
    Public Class Form1
        Private Sub Button7_Click(sender As Object, e As EventArgs) Handles Button7.Click
            Try
                Dim value As String = TextBox5.Text
                Dim formattedValue As String = FormatLargeNumber(value)
                TextBox5.Text = formattedValue
            Catch ex As Exception
                MessageBox.Show(ex.Message, "Formatting Error")
            End Try
        End Sub
    
        Private Function FormatLargeNumber(value As String) As String
            Dim myLong As ULong
            If (Not ULong.TryParse(value, myLong)) Then
                Throw New Exception("Invalid unsigned long.")
            End If
            Return myLong.ToString("#,##0")
        End Function
    End Class
    This does a couple of things:
    1. It turns option strict on. For more information, check out https://www.vblessons.com/lessons.html#/1/2
    2. It defines the FormatLargeNumber function to adhere to the SRP
    3. It binds to Button7's click event
      1. It wraps the code in a try/catch so that if anything fails, a message appears
      2. It gets the value from the TextBox
      3. It formats the value by calling the FormatLargeNumber method
      4. It sets the value of the TextBox to the formatted value
    "Code is like humor. When you have to explain it, it is bad." - Cory House
    VbLessons | Code Tags | Sword of Fury - Jameram

  19. #19

    Thread Starter
    Lively Member
    Join Date
    Dec 2024
    Posts
    95

    Re: Having problems with this experiment code

    My very first Function.... yayyyyy.
    And I reduced all the code in the Sub to just one line of code.

    Code:
    Private Sub Button7_Click(sender As Object, e As EventArgs) Handles Button7.Click
        'Ford Prefect's original post...
        'Dim myInteger As Int64 = 999999999999999999
        'Dim myString As String = myInteger.ToString("#,##0")
        '-----------------------------------------------------
    
        'What I came up with...
        'Dim myInteger As Int64 = 0
        'myInteger = Convert.ToString(TextBox5.Text)
        'Dim myString As String = myInteger.ToString("#,##0")
        'TextBox5.Text = Convert.ToString(myInteger)
        'TextBox6.Text = myString
        TextBox6.Text = add_Commas(TextBox5.Text)
    
    End Sub
    
    Private Function add_Commas(ByVal a As String) As String  'We are expecting the return value to be a string.
        Dim myInteger As Int64 = 0
        myInteger = Convert.ToString(a)
        Dim myString As String = myInteger.ToString("#,##0")
        Return myString
    End Function

  20. #20

    Thread Starter
    Lively Member
    Join Date
    Dec 2024
    Posts
    95

    Re: Having problems with this experiment code

    Quote Originally Posted by PlausiblyDamp View Post
    Option Strict being off doesn't mean your code is running perfectly, it simply means vb isn't warning you about potential problems.

    If you put something that isn't a number in the textbox then it isn't going to be perfect.

    Just because the right answer comes out doesn't mean the code is correct, using Convert.ToString on a string is a waste of time because a string is already a string and doesn't need converting.
    This is just a practice exercise for me in two areas.

    1) To learn how to put commas into numbers
    2) To learn how write a function.

    The information I learned here allows me to take this to my Temperature Converter program where the user has the option to write any temperature up to 99999999999999999 degrees and convert it to either Fahrenheit or Celsius.

    The user can't enter anything other than numbers or the minus sign. I already took care of that problem.

    etc,etc, etc
    Last edited by Sonny McGhee; Jan 23rd, 2025 at 04:57 PM.

  21. #21

    Thread Starter
    Lively Member
    Join Date
    Dec 2024
    Posts
    95

    Re: Having problems with this experiment code

    Can anyone tell me what code I should be using in my function?

  22. #22
    Powered By Medtronic dbasnett's Avatar
    Join Date
    Dec 2007
    Location
    Jefferson City, MO
    Posts
    9,846

    Re: Having problems with this experiment code

    Quote Originally Posted by Sonny McGhee View Post
    Can anyone tell me what code I should be using in my function?
    Why so complicated?

    Code:
        Private Sub Button7_Click(sender As Object, e As EventArgs) Handles Button7.Click
            Dim theNumber As ULong = 0UL
            If ULong.TryParse(TextBox5.Text, theNumber) Then
                'see
                '  https://learn.microsoft.com/en-us/dotnet/standard/base-types/standard-numeric-format-strings
                TextBox6.Text = theNumber.ToString("n0") 'no leading zeros, commas, no decimals
            Else
                TextBox6.Text = "Invalid input"
            End If
        End Sub
    My First Computer -- Documentation Link (RT?M) -- Using the Debugger -- Prime Number Sieve
    Counting Bits -- Subnet Calculator -- UI Guidelines -- >> SerialPort Answer <<

    "Those who use Application.DoEvents have no idea what it does and those who know what it does never use it." John Wein

  23. #23

    Thread Starter
    Lively Member
    Join Date
    Dec 2024
    Posts
    95

    Re: Having problems with this experiment code

    It worked perfectly, thank you!

    Now I'm going to go through it line by line until it makes sense to me.
    Last edited by Sonny McGhee; Jan 24th, 2025 at 02:53 PM.

  24. #24
    Super Moderator dday9's Avatar
    Join Date
    Mar 2011
    Location
    South Louisiana
    Posts
    12,064

    Re: Having problems with this experiment code

    Quote Originally Posted by Sonny McGhee View Post
    It worked perfectly, thank you!

    Now I'm going to go through it line by line until it makes sense to me.
    Just curious, did you see post #22?
    "Code is like humor. When you have to explain it, it is bad." - Cory House
    VbLessons | Code Tags | Sword of Fury - Jameram

  25. #25

    Thread Starter
    Lively Member
    Join Date
    Dec 2024
    Posts
    95

    Re: Having problems with this experiment code

    Quote Originally Posted by dday9 View Post
    Just curious, did you see post #22?
    Yes, and to me (having only been at this programming thing for two months) I was completely lost and felt stupid that I couldn't figure out what was what and what the code meant. I'm trying to learn and get up to speed but at 79 years old my forgetfulness is a hindrance.

    I apologize.

  26. #26
    Super Moderator dday9's Avatar
    Join Date
    Mar 2011
    Location
    South Louisiana
    Posts
    12,064

    Re: [RESOLVED] Having problems with this experiment code

    It's only natural to feel embarrassed when learning something new. The one thing that you can count on with VBForums is that our community is very supportive as long as we can see that you are putting in the work. Nothing you have posted so far seems to suggest that you aren't putting in the work, you should be commended for how far you have come. The last thing you should feel is embarrassment or hesitancy, we want you to succeed.
    "Code is like humor. When you have to explain it, it is bad." - Cory House
    VbLessons | Code Tags | Sword of Fury - Jameram

  27. #27

    Thread Starter
    Lively Member
    Join Date
    Dec 2024
    Posts
    95

    Re: [RESOLVED] Having problems with this experiment code

    Quote Originally Posted by dday9 View Post
    It's only natural to feel embarrassed when learning something new. The one thing that you can count on with VBForums is that our community is very supportive as long as we can see that you are putting in the work. Nothing you have posted so far seems to suggest that you aren't putting in the work, you should be commended for how far you have come. The last thing you should feel is embarrassment or hesitancy, we want you to succeed.
    Thank You!

  28. #28

    Thread Starter
    Lively Member
    Join Date
    Dec 2024
    Posts
    95

    Re: [RESOLVED] Having problems with this experiment code

    Quote Originally Posted by FordPrefect View Post
    Hi

    Similar ages. When you get a reply containing code, do you try it out in a new Test Project or do you just try to follow it from reading the post?
    If you try the code in a Test Project, you would be able to single line step through the code seeing the variable values change as you go. Have you tried any of that?
    In my Visual Studio, I have at LEAST 50 Solutions started. All for practicing what I find here.

  29. #29

    Thread Starter
    Lively Member
    Join Date
    Dec 2024
    Posts
    95

    Re: [RESOLVED] Having problems with this experiment code

    Quote Originally Posted by FordPrefect View Post
    Hi
    That is good. Have tou mad progress on understanding the various concepts in those? Have you managed to use the basic Debug tools such as Breakpoints, single stepping etc?
    I'm not familiar with either of those terms, yet.

  30. #30

    Thread Starter
    Lively Member
    Join Date
    Dec 2024
    Posts
    95

    Re: [RESOLVED] Having problems with this experiment code

    Quote Originally Posted by FordPrefect View Post
    Hi

    Those are 2 of the most handy tools.

    The first: Breakpoint. Is so easy to set. Just click on the extreme left margin of the editor on a code line where you want the execution to stop. When no longer needed, just click once more - it toggles on/off.

    When (and IF) execution reaches the Breakpoint, execution stops allowing you to examine the values of the variables etc. which can be done simply by hovering the mouse pointer over the variable and it will pop up a small 'hint' box showing the value.

    Single stepping: At any point, from any Breakpoint, you can Continue execution with the Toolbar button, or, use F8 to single step line by line anf the same hover mouse examinations apply there too.

    There are very many other debug tools bit those are the most common ones.
    Well, I'll be damned. Never heard of that, but you can bet I'll be doing exactly what you said above!

  31. #31
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    39,755

    Re: [RESOLVED] Having problems with this experiment code

    I learned about breakpoints the easy way: A cat was standing on my shoulder. It jumped onto the keyboard and set a breakpoint. I had no idea what that was, at the time, but I had to learn what it was to make it go away.

    The lesson here is: A cat can help you learn to code by pressing buttons at random and screwing things up in novel ways.

    A second point that has nothing much to do with coding directly is this: Why bother allowing for temperatures in the range that you are allowing? A temperature of -99999999999999999 is not even theoretically possible, as it is far below absolute zero, while a temperature of positive 99999999999999999 is ONLY theoretically possible, since the atoms would have broken down long ago. And that opens up the programming aspect of that point: There is a control that would have allowed you to skip all of this, though this discussion was still useful, especially the part about Option Strict, which should always be ON (except for the VERY rare situation where you need late binding...which you do not).

    If you were to use the NumericUpDown control (NUD), then ONLY numbers can be entered, and you can set the range yourself. You could set the bottom value to absolute zero, and the upper value to something a bit higher than the temperature of the sun. Anything beyond that range gets into strange physics. The NUD avoids many of the issues that a textbox has. For example, the .Value property is a Decimal, which can be easily converted to either a Double or any type of integer you wanted. More easily than the techniques you have used, in fact. More importantly, ONLY numbers can be entered into the NUD. You said you dealt with that for a textbox, but dealing with all the edge cases available with a textbox is really quite tricky. For example, a person could cut and paste into the textbox. That will bypass most of the simpler means of restricting entry. The NUD doesn't have those edge cases and is therefore, better for numbers.
    My usual boring signature: Nothing

  32. #32

    Thread Starter
    Lively Member
    Join Date
    Dec 2024
    Posts
    95

    Re: [RESOLVED] Having problems with this experiment code

    Hi Shaggy Hiker,

    In regards to...
    A second point that has nothing much to do with coding directly is this: Why bother allowing for temperatures in the range that you are allowing? A temperature of -99999999999999999 is not even theoretically possible, as it is far below absolute zero, while a temperature of positive 99999999999999999 is ONLY theoretically possible, since the atoms would have broken down long ago. And that opens up the programming aspect of that point: There is a control that would have allowed you to skip all of this, though this discussion was still useful, especially the part about Option Strict, which should always be ON (except for the VERY rare situation where you need late binding...which you do not).
    Yep, I've already set the program to display an error message if the user temps below absolute zero

    In fact, in they do, A Picture Box pops up of the HAL 9000 Computer, and a sound clip of Hal saying "I'm sorry, I can not allow that". I did this because I discovered 'References' and figured I'd practice using them in my code.

    As for the high temps, I did it for the practice of learning and writing code.

    I try to work on learning code about 4-5 hours every day.Name:  Screenshot.jpg
Views: 161
Size:  35.5 KB

  33. #33

    Thread Starter
    Lively Member
    Join Date
    Dec 2024
    Posts
    95

    Re: [RESOLVED] Having problems with this experiment code

    And this screenshot is the reason I started this thread. For some reason I decided that a properly formatted (with commas) result would look better. Necessary? Hell no! But necessary for me if I'm going to learn to be a better coder.

    Name:  Screenshot2.jpg
Views: 153
Size:  26.5 KB

  34. #34
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    39,755

    Re: [RESOLVED] Having problems with this experiment code

    One thing you might consider is doing the conversion on TextChanged. That would have an interesting effect. Whether you LIKE that effect is a different question, but it would be interesting. As each character is typed (except for the minus sign), you'd get a conversion of whatever was in the textbox. Of course, that would require something other than buttons, such as radiobuttons such that you are either going F to C or C to F (whichever you set as a default) before anything gets entered.
    My usual boring signature: Nothing

  35. #35
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    39,755

    Re: [RESOLVED] Having problems with this experiment code

    By the way, you are using reference types ALL the time in VB.NET. Anything that isn't one of the basic data types like integers, doubles, dates, and so forth is a reference type. Even strings are reference types, though they behave a bit oddly. Since everything else is a reference type, controls, forms, and everything else, are reference types.
    My usual boring signature: Nothing

  36. #36

    Thread Starter
    Lively Member
    Join Date
    Dec 2024
    Posts
    95

    Re: [RESOLVED] Having problems with this experiment code

    Quote Originally Posted by FordPrefect View Post
    Hi

    Those are 2 of the most handy tools.

    The first: Breakpoint. Is so easy to set. Just click on the extreme left margin of the editor on a code line where you want the execution to stop. When no longer needed, just click once more - it toggles on/off.

    When (and IF) execution reaches the Breakpoint, execution stops allowing you to examine the values of the variables etc. which can be done simply by hovering the mouse pointer over the variable and it will pop up a small 'hint' box showing the value.

    Single stepping: At any point, from any Breakpoint, you can Continue execution with the Toolbar button, or, use F8 to single step line by line anf the same hover mouse examinations apply there too.

    There are very many other debug tools bit those are the most common ones.
    Man, I finally figured out these breakpoints and single stepping through code, and wow.... it's the best thing since sliced bread. I've been using the hell out of it to pinpoint errors in my coding. Thanks for that tip!

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width