Format String to Currency

J

Joshua

I've seen many post regarding this, but I have yet to find what I
need. I have a string that can contain numbers as well as text
(legacy data was poorly designed and I have to deal with it). In the
instance that the string is a number, or decimal i would like to
format it as a currency otherwise I'd like to leave it as is.

So, the string could be (all of these are possible):
Type 1
Type A
123
123.33
123.00000003
Type 1 < 2

and I would like to format the ones that are numbers, so I'd like to
format it as such:
Type 1
Type A
$ 123.00
$ 123.33
$ 123.00
Type 1 < 2

Does anybody have any good tricks or something? I guess I could do a
series of casts, using the try catch option? Any help would be
greatly appreciated.

Thank you.
 
M

Mark Rae [MVP]

Does anybody have any good tricks or something? I guess I could do a
series of casts, using the try catch option? Any help would be
greatly appreciated.

string strNumber = "<string to evaluate>";
decimal decTest;
if(Decimal.TryParse(strNumber, NumberStyles.Number, null, out decTest))
{
strNumber = "$" + Convert.ToDecimal(strNumber).ToString("#,##0.00");
}
 
G

Ghostman

I agree with Mark's post, except i'd change it to


string strNumber = "<string to evaluate>";
decimal decTest;
if(Decimal.TryParse(strNumber, NumberStyles.Number, null, out
decTest))
{
strNumber = "$" + decTest.ToString("#,##0.00");

}


Unless there's a reason to convert it twice...
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,754
Messages
2,569,528
Members
45,000
Latest member
MurrayKeync

Latest Threads

Top