Formating Text box

saidev

Active member
Joined
Dec 22, 2005
Messages
27
Programming Experience
1-3
Hi guys,
I have a text box with "1542.00000" i want to format it to "$1,542.00"
can you guys help me with code in VB.NET
Thanks,
 
As the Currency data type is not supported in VB7 (.NET) but instead, there is a new data type named Decimal (directly supported by the .NET Framework and Runtime), which can handle more digits on both sides of the decimal point, for all money variables and calculations i would suggest to follow this recommendation even there is a way to use Currency in vb.net yet.

The sign dollar $ or any other you can just add/conatenate later or yet better to put it in a label control ahead of the textBox.
The way which i prefer is as it follows:
VB.NET:
[COLOR=blue]Dim [/COLOR]amount [COLOR=blue]as[/COLOR] [COLOR=blue]Decimal[/COLOR] = [COLOR=blue]CType[/COLOR](TextBox1.Text, [COLOR=blue]Decimal[/COLOR]) [COLOR=green]'say you have entered 1400.10345[/COLOR][SIZE=2][COLOR=#0000ff]
Me[/COLOR][/SIZE][SIZE=2].TextBox1.Text = [/SIZE][SIZE=2][COLOR=#0000ff]String[/COLOR][/SIZE][SIZE=2].Format("{0:n2}", amount) [COLOR=green]'the result after formating will look like 1,400.10[/COLOR][/SIZE]

Regards ;)

 
With a little more code we got currency formatting with the NumberFormatInfo class (NFI). For this example I used the standard american culture, that seemed to fit the question asked, but NFI is easy to customize for other predefined cultures and other user needs.

What I do here is to parse the number string into a Decimal, then reformat it as currency string with culture dependent NFI
VB.NET:
[SIZE=2][COLOR=#0000ff]Dim[/COLOR][/SIZE][SIZE=2] nfi [/SIZE][SIZE=2][COLOR=#0000ff]As[/COLOR][/SIZE][SIZE=2] NumberFormatInfo = [/SIZE][SIZE=2][COLOR=#0000ff]New[/COLOR][/SIZE][SIZE=2] CultureInfo("en-US", [/SIZE][SIZE=2][COLOR=#0000ff]False[/COLOR][/SIZE][SIZE=2]).NumberFormat
[/SIZE][SIZE=2][COLOR=#0000ff]Dim[/COLOR][/SIZE][SIZE=2] num [/SIZE][SIZE=2][COLOR=#0000ff]As[/COLOR][/SIZE][SIZE=2] [/SIZE][SIZE=2][COLOR=#0000ff]Decimal[/COLOR][/SIZE][SIZE=2] = [/SIZE][SIZE=2][COLOR=#0000ff]Decimal[/COLOR][/SIZE][SIZE=2].Parse("1542.00000".Replace(".", NumberFormatInfo.CurrentInfo.NumberDecimalSeparator))
MsgBox(num.ToString("C", nfi))
[/SIZE]

If you were running in an US culture defined computer, you could just do
num.ToString("C") and the default currency NFI was used, which would give the requested result.

Observe that I am replacing the given decimal delimiter with another. The reason is that I belong to a culture that doesn't recognize "." as a decimal delimiter (we incidently use ","), which result in a parse exception when reading the number string.
 
Back
Top