.NET FAQs Unleashed!
 
    
    

How to format and display a decimal number as a currency string?

.NET provides a number of ways to format and then display strings. Say we declare a decimal and assign it a value, and then say we have to display the number as a currency, then we may do the following:

Decimal amount = 502500.7546M;

string str = amount.ToString(“C”);

Notice here that we have used the virtual ToString() method to convert the decimal to a string type. After that, we have used the “C” character to make sure that the variable str is displayed as a currency. To display the output, we can write

Console.WriteLine(str);

This would display

$502,500.75

You may see that the output is

  • Rounded to two decimal places
  • You will see a comma in the displayed output
  • You will see the $ symbol

If we set “C3” as the value in the ToString() method, then the ‘3’ would signify that the displayed output would be up to 3 decimal places.

Definition   Display 5555 as 0005555   Initialize string from a char[]   Format decimal as currency   Output int type as hexadecimal string   Display a number in exponential   Display a number as a percent   Is String a reference type   ToString("F2")    @ before double quotes   Carriage return   Escape Sequence Why do we use backslash characters with strings?   String VS. string   \u0042\u0041\u0044  

More Interview Questions.....