bonny
bonny

Reputation: 738

Need help in FORMAT function

I wrote a code and want to convert the value like if user write 12, it should be converted into "12.00" Reffered link

I referred the link above and got a "Format" function but when I tried it in my project, it converts the value into "0.00"

My code I written below...

    Private Sub txtDisc_KeyDown(sender As Object, e As System.Windows.Forms.KeyEventArgs) Handles txtDisc.KeyDown
    If e.KeyCode = Keys.Return Then
        txtDisc.Text = Format(txtDisc.Text, "0.00")
        txtOpeningBal.Focus()
    End If
End Sub

Please help me if I made any mistake in writing the code..

I am totally new with this function and also seen msdn helps but cannot understand it properly...

Upvotes: 3

Views: 458

Answers (3)

shadow
shadow

Reputation: 1903

You have to cast the text value to a number (double perhaps?) to perform format against.

Check this example:

Sub Main()
        Dim s As String = "12"
        Dim d As Double = Double.Parse(s)

        Console.WriteLine(d.ToString("#,##0.00"))
        Console.WriteLine(d.ToString("C1"))
        Console.WriteLine(d.ToString("C3"))
        Console.WriteLine(String.Format("{0:C2}", d))
        Console.WriteLine(String.Format("{0:C5}", d))

        Console.ReadLine()
    End Sub

"C" is for currency

Upvotes: 2

Rowland Shaw
Rowland Shaw

Reputation: 38130

You need to convert the string txtDisc.Text to a numeric value, before passing it to the Format() method.

You could do something like:

txtDisc.Text = Format(Val(txtDisc.Text), "0.00")

Or you could parse the value, and use the .Net methods (rather than the VB6 compatibility methods), so something like:

Dim disc As Double
If Double.TryParse(txtDisc.Text, disc) Then
    txtDisc.Text = string.Format("{0:N2}", disc)
End If

Upvotes: 9

miroxlav
miroxlav

Reputation: 12184

First, you must parse your text input to get a numeric value. Then you can format it as you wish.

   txtDisc.Text = Format(Val(txtDisc.Text), "0.00")

Note: Val function is old approach, recommended one is through Double.Parse(), but I think in this simple example, you don't care.

Upvotes: 4

Related Questions