Home
Search
 
What's New
Index
Books
Links
Q & A
Newsletter
Banners
 
Feedback
Tip Jar
 
C# Helper...
 
XML RSS Feed
Follow VBHelper on Twitter
 
 
 
MSDN Visual Basic Community
 
 
 
 
 
TitleUse standard formatting strings to format Doubles in VB .NET
DescriptionThis example shows how to use standard formatting strings to format Doubles in VB .NET.
Keywordsformat, format specifier, string, VB.NET
CategoriesVB.NET, Strings
 
The Double class's ToString method formats a Double value. For example, the following code displays a value in fixed-point (the F specifier).

    Debug.WriteLine(value.ToString("F"))

The standard formatting characters are:

  • C - Currency
  • D - Decimal
  • E - Scientific notation (exponential)
  • F - Fixed-point
  • G - General
  • N - Number
  • P - Percent
  • R - Round-trip (the result can be parsed to the original value)
  • X - Hexadecimal
This example program lets you enter values and enter or pick format strings to see the results. When you change the value or format string, the ShowValue routine displays the result. The subroutine treats the value as an integer if it has no fractional part so you can test the D and X, which only work for integers. It uses the leftmost character displayed by the cboFormat ComboBox (for example, this might be "D - Decimal").
 
Private Sub ShowValue()
    Try
        ' Get the value.
        Dim value As Double = Double.Parse(txtValue.Text)
        Dim ivalue As Integer = CInt(value)

        ' See if it's an integer.
        If value = ivalue Then
            ' It's an integer. Treat it as one so D and X
            ' work.
            txtResult.Text = _
                ivalue.ToString(cboFormat.Text.Substring(0, _
                1))
        Else
            txtResult.Text = _
                value.ToString(cboFormat.Text.Substring(0, _
                1))
        End If
    Catch ex As Exception
        txtResult.Text = ""
    End Try
End Sub
 
Experiment with it and consult the online help about format strings to learn more.
 
 
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated