Three Ways To Add Thousand Separator For A Number In A TextBox Using C#

One of the most important things in a commercial software project is the price parameter that we might ask clients to insert into the software. Since reading numbers that are greater than 1000, without a thousand separators is hard for us, we need to have a feature that can add a thousand separators to different types of numbers. In the following blog, you will understand how to add a thousand separators for a number in a TextBox or the other controllers such as labels.

Method 1 - Add a thousand separator to a TextBox

If you want to add a thousand separator to a TextBox immediately after the client enters a number to the TextBox you can use the code below in the TextChanged event of the TextBox.

private void textBox1_TextChanged(object sender, EventArgs e)
{
    if (textBox1.Text == "" || textBox1.Text == "0") return;                         
    decimal number;                                                                   
    number = decimal.Parse(textBox1.Text, System.Globalization.NumberStyles.Currency);
    textBox1.Text = number.ToString("#,#");                                           
    textBox1.SelectionStart = textBox1.Text.Length;                                  
}

e.g: the code converts 1500 to 1,500

Method 2 - Add a thousand separator to Label

If you want to add a thousand separators to a label that its text is stable and does not change as a TextBox, you can use the code below that uses NumberFormatInfo helper class.

    var separator= new System.Globalization.NumberFormatInfo() {
        NumberDecimalDigits = 0,
        NumberGroupSeparator = "."
    };

    var import = 1234567890;
    var export = import.ToString("N", separator);

In this example, you can change the NumberGroupSeparator value based on your region. For example in the Middle east you should use "," instead of "." unlike in Europe.

Method 3 - The easiest way to do it

The easiest way to add a thousand separator to a text in a TextBox or a Label is to use the ToString("N") method like the code below,

Convert.ToDouble("1234567.12345").ToString("N")

Don't forget that in this example, you can add a thousand separator to a double variable and if you want to add it to an integer variable you've to convert it to a double.

How can we use a string that contains a number with a thousands separator as a number variable?

In this case, you can use Replace method to remove a thousand separators and use Parse or Convert methods to convert a string to a number. for example,

string import = 123,456,789;
int export = int.Parse(import.Replace(",",""));

That's it. Have a nice time with coding!