How to Format Numerical Data in C#


0

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);

Response.Write(outputStr);

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


Like it? Share with your friends!

0

What's Your Reaction?

hate hate
0
hate
confused confused
0
confused
fail fail
0
fail
fun fun
0
fun
geeky geeky
0
geeky
love love
0
love
lol lol
0
lol
omg omg
0
omg
win win
0
win
Anand Narayanaswamy
Anand Narayanaswamy is the editor-in-chief of Learnxpress. He was a Microsoft Most Valuable Professional (MVP) for a period of 9 years. He is a ASPInsider based in Trivandrum, Kerala State, India. Anand is the author of Community Server Quickly published by Packt Publishing.

0 Comments

Your email address will not be published. Required fields are marked *