Search code examples
c#winformstext

Separate the three-digit numbers in Windows form(C # ) and return them to the original state


In Windows Form (C #), I enter my number in the text box and separate the three digits with the following code (for better readability of the number). For example, the:

2500000 => 2,500,000

But I have a problem!

I want to do math operations (addition, multiplication, etc.) on my numbers. And I need to return my number to the first state (2500000) !?

please guide me This is my code:

private void textBox1_TextChanged_1(object sender, EventArgs e)

    {

        if (textBox1.Text == "")
        {
            textBox1.Text = "0";
        }
        textBox1.Text = long.Parse(textBox1.Text.Replace(",", "")).ToString("n0");
        textBox1.SelectionStart = textBox1.Text.Length;
    }

Solution

  • Since the Text property is a string, you will need to parse it to a number in order to make math operations. You can do this safely by calling the TryParse method.

    if (long.TryParse(textBox1.Text, NumberStyles.AllowThousands, CultureInfo.CurrentCulture, out var number))
    {
        // number is now of type long
        number += number;
    }
    

    By the way, in your example you remove the commas by replacing them with an empty string, but then you put them back by calling .ToString("n0").