Link to home
Start Free TrialLog in
Avatar of khyberman
khyberman

asked on

Currency Formay

How can i convert a long into a string with currency format, for example

long a = 2000000

 i ould like to print:
2,000,000


Thanks,






Avatar of PoeticAudio
PoeticAudio

currency, like with a "$", too?
long a = 2000000

string curr = String.Format("{0:c}", a);
if you don't want the $ you can use

string curr = String.Format("{0:N}", a));
ASKER CERTIFIED SOLUTION
Avatar of PoeticAudio
PoeticAudio

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
I would suggest you make a Currency or Money class to hide the conversion implementation to make your code more flexible and cleaner.  For example you can do something like this:

Money m = new Money(2000000);
Console.Writeline(m);  // You can output any where, like in a Form or something, it doesn't have to be console
// output would be $200,000

I would also overload the +,-,*,/ and == operators, so you can do cool things like:

Money m1 = new Money(5000);
Money m2 = new Money(5000);
Money m3 = m1 + m2 ;
Console.Writeline(m3);  // this will output $10,000

Basically you have a constructor that takes in a long or double, and you'll have to override the ToString() method.  In the ToString() method you'll basically call the String.Format().

This way, you don't have to litter String.Format every where in your code.  If you decide to change how the Currency is formated, you can just change the Money object itself, everything will work.  Otherwise you'll have to hunt down the places you did String.Format().

The Money class I shown can be a struct if you like, but it's fine being an object.

Cheers,

Aaron
http://aaronfeng.blogspot.com/