Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to format a Windows Forms Textbox with thousand separator and decimal separtor for numeric input

I'm new to Windows Forms and try to do something. I'm using C#.

I'm using Windows Forms and I've put eight textboxes on my form, and all are numeric with decimal value.

I like to achieve the results below. My decimal separator is a comma and thousand separator is a dot. I've ever seen something like ##.###,## or whatever, but don't remember.... How can i achieve the below approach?

So the idea is when I type 1234 and leave the focus from the textbox it should format and when I get in the textbox back again the thousand separator should not format only the decimal separator.

I think I've to use some events like LostFocus.

Input                 Result

1234                1.234,00

12.34                    12,34

12,34                    12,34

1234567     1.234.567,00

12,34                    12,34

12345,67     12.345,67

like image 388
ethem Avatar asked Mar 18 '13 09:03

ethem


1 Answers

On your LostFocus event in the textbox, use:

textBox1.Text = string.Format("{0:#,##0.00}", double.Parse(textBox1.Text));

Make sure that the text is double / integer first before applying the above logic or it will throw an exception. This solution is rather harsh, tough.

If you want the format to be in a specific culture rather than your current computer's culture, then

textBox1.Text = string.Format(System.Globalization.CultureInfo.GetCultureInfo("id-ID"), "{0:#,##0.00}", double.Parse(textBox1.Text));

The above example is for the Indonesian currency format, in which the thousand separator use dot (".") rather than comma (",").

like image 128
Fendy Avatar answered Sep 25 '22 07:09

Fendy