We help IT Professionals succeed at work.

Formatting Decimal Places in Visual Basic 2008

jampost
jampost asked
on
I am trying to limit the decimal places in various TextBoxes to two.  "Currency" I have tried a few ways unsuccessfully.

I tried this Code:

 Private Sub BtnNet_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnNet.Click

        TB_NetPay.Text = Format(TB_NetPay.Text, "#0.00")
        TB_NetPay.Text = (TBGP.Text - TBT.Text - TextBox0.Text - Medicare2.Text - TextBox5.Text)


    End Sub
Comment
Watch Question

Kyle AbrahamsSenior .Net Developer
CERTIFIED EXPERT

Commented:
try:
   TB_NetPay.Text = Format(TB_NetPay.Text, "c")
CERTIFIED EXPERT
Most Valuable Expert 2011
Top Expert 2015
Commented:
Your second line overwrites whatever the first line has written. On top of that, you are relying on implicit conversion, which is almost always never a good idea. My suggestion would be to refactor your code a tad:

Private Sub BtnNet_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnNet.Click
    Dim decTBGP As Decimal
    Dim decTBT As Decimal
    Dim decTB0 As Decimal
    Dim decTBMedCare As Decimal
    Dim decTB5 As Decimal
    
    If Decimal.TryParse(TBGP.Text, decTBGP) AndAlso _
       Decimal.TryParse(TBT.Text, decTBT) AndAlso _
       Decimal.TryParse(TextBox0.Text, decTB0) AndAlso _
       Decimal.TryParse(Medicare2.Text, decTBMedCare) AndAlso _
       Decimal.TryParse(TextBox5.Text, decTB5) Then
       
        Dim total As Decimal = (decTBGP - decTBT - decTB0 - decTBMedCare - decTB5)
    
        TB_NetPay.Text = total.ToString("#,##0.00")    
    
End Sub

Open in new window

jampostGeneral Maanager

Author

Commented:
ged325

TB_NetPay.Text = Format(TB_NetPay.Text, "c")    had no effect, but it did not cause any errors.
jampostGeneral Maanager

Author

Commented:
kaufmed:


 Thank you.  I think what you are saying about implicit conversion is something I realy need to work on. Thanks again  -  You knocked it out of the park, as usual.
CERTIFIED EXPERT
Most Valuable Expert 2011
Top Expert 2015

Commented:
NP. Glad to help  = )

Explore More ContentExplore courses, solutions, and other research materials related to this topic.