-2

I am creating a simple console app which I use the Currency format specifier. But I want it to be the sharpest way.

I've done this way:

class Account
{
        public int Number { get; set; }
        public string Holder { get; set; }
        public double Balance { get; protected set; }

        public Account(int number, string holder, double balance)
        {
            Number = number;
            Holder = holder;
            Balance = balance;
        }
}


static void Main(string[] args)
{
       Account acc = new Account(8010, "Bob", 100);

       Console.WriteLine($"{acc.Balance:C}");
}

I want to know if this is the lesser typing and best way of doing it. What do you guys think?

1 Answers1

0

It's not clear which part of your code you're seeking a shorter way to implement, but since you mention the currency format specifier a couple times I assume your question boils down to simply...

Is there a shorter way than this to write a currency-formatted number to the console?

double balance = 100;

Console.WriteLine($"{balance:C}");

There are a few options that produce the same result...

Console.WriteLine($"{balance:C}");
Console.WriteLine("{0:C}", balance);
Console.WriteLine(balance.ToString("C"));
Console.WriteLine(string.Format("{0:C}", balance));

...but one can't really expect to get much shorter than an interpolated string with a single-character format specifier.

Note that all of the above format a currency string using the culture of the current thread. If you want to perform formatting using a specific culture then your options become fewer and longer...

CultureInfo culture = CultureInfo.InvariantCulture;

Console.WriteLine(balance.ToString("C", culture));
Console.WriteLine(string.Format(culture, "{0:C}", balance));

As @NicoD pointed out in the comments, for storing currency you'll also want to look into using the decimal type instead of float or double:

Lance U. Matthews
  • 15,725
  • 6
  • 48
  • 68