Convert a Number into a Formatted String

Problem

You want to convert a numeric type (Decimal, Int32, Double, and so on) into a formatted string.

Solution

Use the overloaded version of the ToString method that accepts a format string.

Discussion

There are two types of numeric format strings: standard and custom. Standard format strings use a preset format according to the current culture and are identified by a single letter. You use that letter, in conjunction with a number that indicates the precision, when converting a number to a string. Here are a few common examples:

Dim Number As Decimal = 12345.6D ' The format specifier for currency is "C" Dim MoneyString As String = Number.ToString("C") ' MoneyString is now "12,345.60" ' The format specifier ...

Get Microsoft® Visual Basic® .NET Programmer's Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.