Currency Formay

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

long a = 2000000

 i ould like to print:


Who is Participating?
oops just noticed syntax error on my last post

string curr = String.Format("{0:N}", a));

should be

string curr = String.Format("{0:N}", a);
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));
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.


Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.