Question How do I add commas in numbers automatically?

love_lyn99

Member
Joined
Sep 2, 2022
Messages
16
Programming Experience
Beginner
Hi! I am creating a system where when i type a number in textbox1, it automatically add commas. ive searched in the internet and found almost similar functions on what i am looking for. but i have a problem, i dont want the < .00 > decimal to show during i enter the numbers and i will only add decimal if needed.

but some codes i found will only add < .00 > or not able to add decimal at all. here's the code im currently using:

TextBox1_TextChanged:
Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
        TextBox1.Text = CDbl(TextBox1.Text).ToString("n0")
        TextBox1.Select(TextBox1.Text.Length, 0)
End Sub

i did put the <("n0") > because i want to not show the decimal, but instead it completely removes decimal (i think). the "." wont show.

i also tried the ("#,###,###") but it has the same result.

for example: val = 123456
output = 123,456
but if i add decimal: it wont show the "."

i add the 3rd line because i want the cursor to be fix at the end.
 
NumericUpDown control has this built in, it is a textbox for numeric input.
 
Your implementation is way too simplistic to do what you want.
NumericUpDown control has this built in, it is a textbox for numeric input.
That's not completely true. I think that the aim here is to format the data as it is entered and to allow a variable number of decimal places, neither of which the NumericUpDown will do.

@love_lyn99, assuming I'm right in my assumptions, what you're doing is woefully inadequate, so you really need to decide whether it's worthwhile. In most cases, it would be more practical to simply allow the user to enter whatever they want and then validate and format when they leave the control. If you're determined to plough ahead, you may need to consider what happens if the user enters invalid data, like letters or multiple decimal points. Assuming that they enter only valid characters, what if they want to insert digits somewhere in the middle of the text and you then shift the caret to the end?
 
I understood the question as for example one input "123" and after user press Enter or navigate away the Textbox shows "123.00" (in local culture formatting). If you set NumericUpDown.DecimalPlaces=2 then that is what will happen. It doesn't show decimal places when entering the number (unless you type some in), but does show them afterwards according to DecimalPlaces setting.
 
Your implementation is way too simplistic to do what you want.

That's not completely true. I think that the aim here is to format the data as it is entered and to allow a variable number of decimal places, neither of which the NumericUpDown will do.

@love_lyn99, assuming I'm right in my assumptions, what you're doing is woefully inadequate, so you really need to decide whether it's worthwhile. In most cases, it would be more practical to simply allow the user to enter whatever they want and then validate and format when they leave the control. If you're determined to plough ahead, you may need to consider what happens if the user enters invalid data, like letters or multiple decimal points. Assuming that they enter only valid characters, what if they want to insert digits somewhere in the middle of the text and you then shift the caret to the end?
hi @jmcilhinney . your assumptions were correct. about the format value when leave the control, i did considered it, i already made a code for it but make it as comment for a while. i was just thinking maybe someone here know how to fix or can give idea.

my idea was based on window calculator's numbering format, when the the number hit thousands, mils, bils etc. it'll automatically adds commas without automatically adding decimal digits like < .00 >. and will only add by user if value has decimal, like a free will. thats why i add the code in < TextBox1_TextChanged() >. but the code im using is either automatically adds decimal < .00 > or completely removes decimal. (ANNEX A). by the way, about the entered data by user, i already include the code for it that if data is not int, (dot) or (minus sign)/(negative), then not allow. (ANNEX B)

hope that clears the understanding.

ANNEX A
---------
comma:
Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
        TextBox1.Text = CDbl(TextBox1.Text).ToString("n0")                          '("n0") = doesnt add decimals. and cannot add decimals. ("n") = includes decimal but automatically includes the .00'
        TextBox1.Select(TextBox1.Text.Length, 0)
End Sub
---------

ANNEX B
----------
limit:
 Private Sub TextBox1_KeyPress(sender As Object, e As KeyPressEventArgs) Handles TextBox1.KeyPress
        If Not Char.IsNumber(e.KeyChar) AndAlso Not Char.IsControl(e.KeyChar) AndAlso Not e.KeyChar = "." AndAlso Not e.KeyChar = "-" Then
            e.Handled = True
        End If
    End Sub
-------------
 
I understood the question as for example one input "123" and after user press Enter or navigate away the Textbox shows "123.00" (in local culture formatting). If you set NumericUpDown.DecimalPlaces=2 then that is what will happen. It doesn't show decimal places when entering the number (unless you type some in), but does show them afterwards according to DecimalPlaces setting.
hi @JohnH . i will concider it, but i need to do research about the numberupdown, it's my first time knowing this. thank you!
 
Your KeyPress code does not prevent the user entering multiple decimal points or multiple negative signs and it doesn't prevent the user pasting anything at all into the control.
 
If you want to format a number and include group separators and an optional decimal point without truncating the decimal, you can use something like this:
VB.NET:
Dim a = 0.0
Dim b = 1.0
Dim c = 123.0
Dim d = 1234.5678

Console.WriteLine(a.ToString("#,0.##########"))
Console.WriteLine(b.ToString("#,0.##########"))
Console.WriteLine(c.ToString("#,0.##########"))
Console.WriteLine(d.ToString("#,0.##########"))
Output:
0
1
123
1,234.5678
That format specifier outputs at least one digit with optional group separators, optional decimal and up to 10 decimal places. If you might have numbers with more decimal places, append more # characters.
 
Mind you, if you were to use code like that on the TextChanged event then it will always remove the decimal point unless the user enters the digits to the right of it first, so there's that. A proper implementation of a numeric TextBox is actually very complex, which is why it's better to simply validate and format the input when the user has finished entering it.
 
If you want to format a number and include group separators and an optional decimal point without truncating the decimal, you can use something like this:
VB.NET:
Dim a = 0.0
Dim b = 1.0
Dim c = 123.0
Dim d = 1234.5678

Console.WriteLine(a.ToString("#,0.##########"))
Console.WriteLine(b.ToString("#,0.##########"))
Console.WriteLine(c.ToString("#,0.##########"))
Console.WriteLine(d.ToString("#,0.##########"))
Output:

That format specifier outputs at least one digit with optional group separators, optional decimal and up to 10 decimal places. If you might have numbers with more decimal places, append more # characters.

Hi @jmcilhinney . i did try the code but modified it a bit, because it gives me string conversion error.

textchange:
Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
        TextBox1.Select(TextBox1.Text.Length, 0)

        Dim val1 = Val(TextBox1.Text)
        TextBox1.Text = val1.ToString("#,0.##")
End Sub

but the problem is, whenever i enter value, it'll remove the other digit except the first one and will only replace the other 2 digits with last 2 digits you've entered.

For example: value = 123456
the output was = 156

Also tried it in keypress event. but when i hit enter twice, it'll remove all digit except the first string. (depending on what you set in ToString("") ) .

I've tried changing the string value but the output was the same.
is it because of the change in code?
 
Visual Studio has a debugger built in. You should use it.
im using debugger. here's the error message.

1663912537834.png
 
You previously had this:
VB.NET:
Dim val1 = Val(TextBox1.Text)
and now, for no apparent reason, you have this:
VB.NET:
Dim val1 = TextBox1.Text
That means that val1 is type String and there is no such ToString method on that type. You can't format a String as though it were a number. If you want to format a number then you have to actually have a number to format.
 
You should set Option Strict On in the project properties and also in the VS options, so it will be On by default for all future projects. That will pickup issues with data types like this at compile time instead of letting them through to run time. That will force you to write better code.
 
Back
Top