-
Jan 22nd, 2025, 02:57 PM
#1
Thread Starter
Member
[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
-
Jan 22nd, 2025, 03:31 PM
#2
Re: Having problems with this experiment code
When you say the output isn't correct, what are you expecting and what are you getting?
-
Jan 22nd, 2025, 03:41 PM
#3
Lively Member
Re: Having problems with this experiment code
Hi
Try using a format like this:
Code:
Dim myUlong As ULong = 999999999999999999
Dim myString As String = myUlong.ToString("#,##0")
and beware overflows (or infinity)
Ooooops: You are using ab Int64m so:
Code:
Dim myInteger As Int64 = 999999999999999999
Dim myString As String = myInteger.ToString("#,##0")
Last edited by FordPrefect; Jan 22nd, 2025 at 03:58 PM.
-
Jan 22nd, 2025, 03:45 PM
#4
Thread Starter
Member
Re: Having problems with this experiment code
When I type in 999999999999999999
The result comes back as 1,000,000,000,000,000,128
-
Jan 22nd, 2025, 03:48 PM
#5
Thread Starter
Member
Re: Having problems with this experiment code
I'm off to try that now.....
-
Jan 22nd, 2025, 04:13 PM
#6
Thread Starter
Member
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.
-
Jan 22nd, 2025, 04:14 PM
#7
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
-
Jan 22nd, 2025, 04:22 PM
#8
Lively Member
Re: Having problems with this experiment code
-
Jan 22nd, 2025, 04:34 PM
#9
Thread Starter
Member
Re: Having problems with this experiment code
 Originally Posted by FordPrefect
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!
-
Jan 22nd, 2025, 05:08 PM
#10
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
-
Jan 22nd, 2025, 05:50 PM
#11
Thread Starter
Member
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!
-
Jan 23rd, 2025, 12:49 PM
#12
Thread Starter
Member
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
-
Jan 23rd, 2025, 01:01 PM
#13
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.
-
Jan 23rd, 2025, 01:14 PM
#14
Thread Starter
Member
Re: Having problems with this experiment code
 Originally Posted by PlausiblyDamp
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.
-
Jan 23rd, 2025, 01:46 PM
#15
Lively Member
Re: Having problems with this experiment code
Hi
You need to be congratulated for making that code work.
Here is a commented example of making a Function which can be though of as a 'reusable' piece of code as it is called whenever needed.
This is ONLY a demo and lacks safeguards for errors.
This DEMO needs a new Project with a Default Form1 containing 3 TextBoxes: TextBox1,TextBox2 and TextBox3. TextBox3 has some Properties changed in the first few lines of code.
To see it in action: put a breakpoint on the 'End Sub' of the Load Event and when reached, hover the mouse over any of the variables to examine the values.
Code:
' Form1 3 defaultmextBoxes
' TextBox1 and TextBox2 for user inputs
' TextBox3 (multiline) to show conversions
Option Strict On
Option Explicit On
Option Infer Off
Public Class Form1
Dim IsStarted As Boolean = False
' a reusable 'Function' rhich takes a string
' and return an Int64 if possible, or, a message
' to say couldn't be converted.
Function MakeMyString(incoming As String) As String
Dim num As Int64
If Int64.TryParse(incoming, num) Then
' found a valid Int64 so return it ib the
' required formar
Dim retString As String = num.ToString("#,##0")
' display in TextBox3
TextBox3.AppendText(retString & vbCrLf)
' Return value
Return retString
End If
' return a note that the supplied 'incoming' string
' could not be converted to an Int64
' display in TextBox3 and display in TextBox3
TextBox3.AppendText("Invalid" & vbCrLf)
Return "Invalid"
End Function
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
' set some Properties forTextBox3
With TextBox3
.Height = ClientRectangle.Height - 50
.Anchor = AnchorStyles.Top Or AnchorStyles.Left Or AnchorStyles.Bottom
.Multiline = True
End With
TextBox1.Text = "888888888888888888"
TextBox2.Text = "777777777777777777"
' now all is set up
IsStarted = True
DoIt()
End Sub
Sub DoIt()
' do not need this to eecute until
' eberything is set ip
If Not IsStarted Then Exit Sub
' these are a selection of uses of the Function
' to show that a single function is reusable and
' makes it uneccessary to write the same code over
' and over
Dim s As String = "999999999999999999"
Dim newstring As String = MakeMyString(s)
Dim n As Int64 = 999999999999999999
Dim newstring2 As String = MakeMyString(n.ToString)
Dim tb1 As String = MakeMyString(TextBox1.Text)
Dim tb2 As String = MakeMyString(TextBox2.Text)
Dim InvalidNumber As String = "1234567891011ABCD"
Dim inv As String = MakeMyString(InvalidNumber)
TextBox3.AppendText("=================" & vbCrLf)
End Sub
Private Sub TextBox_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged, TextBox2.TextChanged
DoIt()
End Sub
End Class
EDIT: Updated to include display when TB1/TB2 text changed.
Last edited by FordPrefect; Jan 23rd, 2025 at 03:51 PM.
-
Jan 23rd, 2025, 02:37 PM
#16
Re: Having problems with this experiment code
 Originally Posted by Sonny McGhee
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?
-
Jan 23rd, 2025, 03:38 PM
#17
Thread Starter
Member
Re: Having problems with this experiment code
 Originally Posted by wes4dbt
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.
-
Jan 23rd, 2025, 03:45 PM
#18
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?
-
Jan 23rd, 2025, 03:46 PM
#19
Lively Member
Re: Having problems with this experiment code
Hi
Option Strict is Off by default, that is why I added it in the code I posted - see it at the top.
-
Jan 23rd, 2025, 04:06 PM
#20
Thread Starter
Member
Re: Having problems with this experiment code
 Originally Posted by wes4dbt
Option strict is off and my code is running perfectly.
-
Jan 23rd, 2025, 04:12 PM
#21
Re: Having problems with this experiment code
 Originally Posted by Sonny McGhee
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.
-
Jan 23rd, 2025, 04:22 PM
#22
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:
- It turns option strict on. For more information, check out https://www.vblessons.com/lessons.html#/1/2
- It defines the FormatLargeNumber function to adhere to the SRP
- It binds to Button7's click event
- It wraps the code in a try/catch so that if anything fails, a message appears
- It gets the value from the TextBox
- It formats the value by calling the FormatLargeNumber method
- It sets the value of the TextBox to the formatted value
-
Jan 23rd, 2025, 04:41 PM
#23
Thread Starter
Member
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
-
Jan 23rd, 2025, 04:54 PM
#24
Thread Starter
Member
Re: Having problems with this experiment code
 Originally Posted by PlausiblyDamp
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.
-
Jan 23rd, 2025, 05:00 PM
#25
Lively Member
Re: Having problems with this experiment code
Hi
Well, I don't want to put a damper on your jubilation, but, (for example):
The line myInteger = Convert.ToString(a)
on the line before you declared myInteger as an Int64 - OK, good, but then you try to assign a String to that variable. String are NOT numbers! If you had switched on Strict, you would have been warned about that. If you want to learn to write good code, then switch on Strict.
BTW: saying "but it is working perfectly!" is no longer valid, and, is untrue!
Last edited by FordPrefect; Jan 23rd, 2025 at 05:19 PM.
-
Jan 23rd, 2025, 05:09 PM
#26
Thread Starter
Member
Re: Having problems with this experiment code
Can anyone tell me what code I should be using in my function?
-
Jan 23rd, 2025, 05:18 PM
#27
Lively Member
Re: Having problems with this experiment code
 Originally Posted by Sonny McGhee
Can anyone tell me what code I should be using in my function?
Just read the posts in this thread. It is all there!
-
Jan 24th, 2025, 11:31 AM
#28
Re: Having problems with this experiment code
 Originally Posted by Sonny McGhee
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
-
Jan 24th, 2025, 02:43 PM
#29
Thread Starter
Member
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.
-
Jan 24th, 2025, 02:58 PM
#30
Re: Having problems with this experiment code
 Originally Posted by Sonny McGhee
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?
-
Jan 24th, 2025, 03:10 PM
#31
Thread Starter
Member
Re: Having problems with this experiment code
 Originally Posted by dday9
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.
-
Jan 24th, 2025, 03:21 PM
#32
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.
-
Jan 24th, 2025, 03:29 PM
#33
Lively Member
Re: [RESOLVED] Having problems with this experiment code
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?
-
Jan 24th, 2025, 03:33 PM
#34
Thread Starter
Member
Re: [RESOLVED] Having problems with this experiment code
 Originally Posted by dday9
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!
-
Jan 24th, 2025, 03:36 PM
#35
Thread Starter
Member
Re: [RESOLVED] Having problems with this experiment code
 Originally Posted by FordPrefect
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.
-
Jan 24th, 2025, 03:40 PM
#36
Lively Member
Re: [RESOLVED] Having problems with this experiment code
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?
-
Jan 24th, 2025, 03:57 PM
#37
Thread Starter
Member
Re: [RESOLVED] Having problems with this experiment code
 Originally Posted by FordPrefect
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.
-
Jan 24th, 2025, 04:19 PM
#38
Lively Member
Re: [RESOLVED] Having problems with this experiment code
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.
-
Jan 24th, 2025, 04:23 PM
#39
Thread Starter
Member
Re: [RESOLVED] Having problems with this experiment code
 Originally Posted by FordPrefect
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!
-
Jan 24th, 2025, 06:50 PM
#40
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
 
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|