How to Format Numerical Data in C#

You will be required to make use of numerical data while programming with C#. This article examines how to format numerical data in C#.

C# ships with several inbuilt formatting specifies which can be used to quickly format a number, for example the ‘c’ specifier will format the number as a currency:

double dbl1 = 7777777.7777777;
outputStr = string.Format(“This is the currency format {0:c}”, dbl1);

This will output the numerical value as a currency based on the user’s current currency setting. In my case this will output:

This is the currency format $10,000,000.00

Note firstly that String.Format is a static method – ie you can not use it from an instance of a string object so the below code will generate a compile error:

string outputStr;outputStr.Format(“This is the currency format {0:c}”, dbl1);

You must always use it at the class level (ie String.Format)

Below are the inbuilt formatting specifiers:
c – Currency
d – Decimal
e – Exponential notation
f – Fixed point formatting
n – Numerical formatting (with commas)
x – Hexidecimal

The below code shows an implementation of the n formatting speficier:

double dbl1 = 7777777.7777777;

string outputStr;

outputStr = string.Format(“This is the numerical format {0:n}”, dbl1);


Note that there will be compile errors if you attempt to format a double using the decimal format. Also, note that hexidecimal expects an integer type.

View the original article here

READ  Programming Entity Framework, Second Edition

Leave a Reply

Your email address will not be published.