tags:

views:

174

answers:

3

I need help with displaying a decimal value on a Windows Form.

I have a class with a method to calculate an interest amount, listed below.

public virtual decimal CalculateInterest()
{
    interest = (interestRate/100) * base.getBalance();
    return interest;
}

In my main form, I am using this method when a button is clicked, listed below.

private void btnCalcInt_Click(object sender, EventArgs e)
{
   decimal endBalance;
   decimal intRate;
   decimal getIntGained;

   endBalance = Convert.ToDecimal(lblSaveEndingBalance.Text);
   intRate = Convert.ToDecimal(lblSaveIntRate.Text);
   SavingsAccount CalcInt = new SavingsAccount(endBalance, intRate);

   getIntGained = CalcInt.CalculateInterest();
   lblSaveInterest.Text = getIntGained.ToString();
}

In the last line (lblSaveInterest.Text = getIntGained.ToString();), how do I tell it to display only 2 positions after the decimal place?

Or, can someone help with this scenario? On my Windows form, I have a text box that represents a percent. Currently, the user could enter a value of 2 or .02. How can I code this to only all .02? By doing this, I could then modify the method in my class and remove the division of 100.

+1  A: 

Try Decimal.Round():

lblSaveInterest.Text = Decimal.Round(getIntGained,2).ToString();
Matthew Jones
+5  A: 

For the first part, you can use either this:

lblSaveInterest.Text = getIntGained.ToString("#,###.00");

Or this:

lblSaveInterest.Text = getIntGained.ToString("G");

EDIT: For the second part, you can add a validation rule for the textbox to display a messagebox if the number is greater than 1.0 (100%) when the textbox loses focus.

Jose Basilio
+1  A: 

I'd also do Decimal.TryParse(string, Decimal) instead of Convert.ToDecimal().

George Stocker