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.
 

JohnH

VB.NET Forum Moderator
Staff member
Joined
Dec 17, 2005
Messages
15,666
Location
Norway
Programming Experience
10+
NumericUpDown control has this built in, it is a textbox for numeric input.
 

jmcilhinney

VB.NET Forum Moderator
Staff member
Joined
Aug 17, 2004
Messages
14,834
Location
Sydney, Australia
Programming Experience
10+
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?
 

JohnH

VB.NET Forum Moderator
Staff member
Joined
Dec 17, 2005
Messages
15,666
Location
Norway
Programming Experience
10+
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.
 

love_lyn99

Member
Joined
Sep 2, 2022
Messages
16
Programming Experience
Beginner
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
-------------
 

love_lyn99

Member
Joined
Sep 2, 2022
Messages
16
Programming Experience
Beginner
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!
 

jmcilhinney

VB.NET Forum Moderator
Staff member
Joined
Aug 17, 2004
Messages
14,834
Location
Sydney, Australia
Programming Experience
10+
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.
 

jmcilhinney

VB.NET Forum Moderator
Staff member
Joined
Aug 17, 2004
Messages
14,834
Location
Sydney, Australia
Programming Experience
10+
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.
 

jmcilhinney

VB.NET Forum Moderator
Staff member
Joined
Aug 17, 2004
Messages
14,834
Location
Sydney, Australia
Programming Experience
10+
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.
 

love_lyn99

Member
Joined
Sep 2, 2022
Messages
16
Programming Experience
Beginner
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?
 

love_lyn99

Member
Joined
Sep 2, 2022
Messages
16
Programming Experience
Beginner
Visual Studio has a debugger built in. You should use it.
im using debugger. here's the error message.

1663912537834.png
 

jmcilhinney

VB.NET Forum Moderator
Staff member
Joined
Aug 17, 2004
Messages
14,834
Location
Sydney, Australia
Programming Experience
10+
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.
 

jmcilhinney

VB.NET Forum Moderator
Staff member
Joined
Aug 17, 2004
Messages
14,834
Location
Sydney, Australia
Programming Experience
10+
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.
 

love_lyn99

Member
Joined
Sep 2, 2022
Messages
16
Programming Experience
Beginner
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.
yiiah. about that. ive tried your code. < Dim a = 0.0 Console.WriteLine(a.ToString("#,0.##########")) > but instead of direct value, i changed it to textbox.text and instead of console output i changed it to textbox output. thats why i got the " unable to cast object of string". but if i set the < Dim a = 123.0 > or something, it doesnt give me error. why is that? is it because the textbox1 value is always string? do i have to add command where it convert textbox1 value to int?
 

jmcilhinney

VB.NET Forum Moderator
Staff member
Joined
Aug 17, 2004
Messages
14,834
Location
Sydney, Australia
Programming Experience
10+
As I have said, if you want to format a number then you need to have a number. In my example code, I used numbers. The Text of a TextBox is a String, not a number. You need to convert the String to a number first. Val will do that, although it's a bad way to do it.
 

love_lyn99

Member
Joined
Sep 2, 2022
Messages
16
Programming Experience
Beginner
As I have said, if you want to format a number then you need to have a number. In my example code, I used numbers. The Text of a TextBox is a String, not a number. You need to convert the String to a number first. Val will do that, although it's a bad way to do it.
i have a problem with the < Val >. like For example: value = 123456 , the output was = 156. but without val, it doest allow me to insert "." . tried changing it with < Dim val1 As Decimal = TextBox1.Text > but its the same, doesnt allow me to insert "." .like its's disabled or something. i guess ill do the < when enter is pressed, format textbox value. > if i can't find solution for it.
 

jmcilhinney

VB.NET Forum Moderator
Staff member
Joined
Aug 17, 2004
Messages
14,834
Location
Sydney, Australia
Programming Experience
10+
I can't see any reason that using Val would do that. It sounds like something is broken somewhere. Please provide step-by-step instructions on how to reproduce that issue and we can see whether we can, indeed, reproduce it.

There's no need to hit Enter. You should probably be handling the Validating and Validated events. The first will allow you to prevent the control losing focus if the contents is not a valid number and the second will allow you to convert the content to a number and then format that as appropriate. The input will then be formatted whenever focus leaves the control. You can still do some work to prevent obviously invalid input, e.g. letters, but tricker stuff can be allowed and validated on leave. That's exactly how a NumericUpDown works.
 

Latest posts

Top Bottom