Software Development optimize

Converting numbers into formatted strings in VB.NET

Irina Medvinskaya presents a simple way to convert the numbers into formatted strings in VB.NET. She also explains the difference between the two types of numeric format strings: standard and custom.

Working with numeric values often requires the ability to convert these values into String values in a particular format. In this article, I'll show you a simple way to convert the numbers (Int32, Decimal, Double, and other datatypes) into formatted strings.

Working with standard numeric format strings

You can convert a numeric value into a string by overloading a version of the ToString method, which accepts a format string.

There are two types of numeric format strings: standard and custom. The standard numeric format strings use one of the predefined formats and are specified by a letter corresponding to a particular format. When converting a number to a string, the letter specifying one of the standard numeric formats is used in combination with a number that refers to a precision to be used during the conversion. Here's an example:

Dim numInfo as Decimal = 11443.4D

Dim strMoney as String = numInfo.ToString("C")

Dim strNormal as String = numInfo.ToString("N")

In this sample, I define the Decimal variable numInfo and set its value. Then, I define the String variable strMoney and convert the value of numInfo into a String in a Currency format. Similarly, I define the String variable strNormal and convert the value of numInfo into a String in a Normal format.

Standard numeric format specifiers

Below is a list of a standard numeric format specifier and its name:

  • C or c: Currency
  • D or d: Decimal
  • E or e: Scientific/Exponential
  • F or f: Fixed-point
  • G or g: General
  • N or n: Number
  • P or p: Percent
  • R or r: Round-trip
  • X or x: Hexadecimal

For more details about these specifiers, check out this table on MSDN.

Custom numeric format specifiers

You can also create custom format strings when the available standard format strings don't satisfy your needs. A custom numeric format string consists of one or more custom numeric format specifiers and defines how numeric data would be formatted. For a full list of custom numeric format specifiers, see the table on MSDN.

Miss a tip?

Check out the Visual Basic archive, and catch up on the most recent editions of Irina Medvinskaya's column.

Advance your scripting skills to the next level with TechRepublic's free Visual Basic newsletter, delivered each Friday. Automatically sign up today!


suk it!!! u nerds and ur computers.....ur all so bumbaclots....dungadinga