Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Error calculating a text field that is formated as currency

Status
Not open for further replies.

MJV57

Programmer
Apr 18, 2009
87
0
0
CA
I have a form with a field cdnsale that is formated as currency but when I try to do a calculation with it it errors out as a division by zero; however if i format it as numerical i do not get this error. Can anyone help me to change my code so I can format as currency and not get this error. My current code is as follows:


decimal cdnsale;
decimal.TryParse (tRECREVHMTextBox.Text,out cdnsale);
decimal profit;
decimal grossprofpercent;

grossprofpercent = Math.Round(profit / cdnsale,2);
 
try parse will set the value to 0 if it encounters an error. this is why the function returns a boolean and uses the out modifier. the reason it's setting the number to zero is the text isn't an known number type (probably because of the currency symbol). below is the proper user of TryParse
Code:
decimal d;
var input = ATextBox.Text;
if(decimal.TryParse(input, out d)
{
   is is a valid decimal
}
else
{
   d is [b]not[/b] a valid decimal
}
you could trim the currency symbol from the text field before parsing
Code:
[COLOR=green]//assuming USD[/color]
var input = ATextBox.Text.Trim("$");

decimal d;
if(decimal.TryParse(input, out d)
{
   is is a valid decimal
}

Jason Meckley
Programmer
Specialty Bakers, Inc.

faq855-7190
faq732-7259
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top