.comment-link {margin-left:.6em;}
My Photo
Name:
Location: Unspecified, Mauritius

I too, am a bug within Māyā.

My Other Blog(s) and Site(s)
Friend sites and blogs
My Recent Posts
Tutorials
Best Articles
My C-Sharp Ideas
Archives
Blog Directories

Thursday, July 21, 2005

 

A few basic things

Decimal Places
[Beginner]


There are quite a few things to know before really getting the hang of C#, and I believe that learning about how to format numbers that need to be output is something pretty basic, that many programmers disregard. However, here's a basic tutorial about controlling the number of decimal places that a decimal type displays.

Let's move on directly to the code. It's simple. Nothing complicated to understand. Check it out:


using System;
using System.Globalization;

namespace NumberFormat
{
/// <summary>
/// MultiParam App
/// </summary>
class Class1
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
NumberFormatInfo myFormat = new NumberFormatInfo();
double d = 15.6781005479;

for (int i=0; i<=10; i++)
{
myFormat.NumberDecimalDigits = i;
Console.WriteLine(i.ToString() +
" decimal digit(s): \t\t"+d.ToString("N", myFormat));
}

Console.ReadLine();
}
}
}


Notice that I've included System.Globalization in the usings. This is a namespace that is required in order to use the NumberFormatInfo class.

What I did was basically to instantiate a NumberFormatInfo class, and play with the NumberDecimalDigits property (which I kept incrementing). Watch the results on a console :) Also, note the use of the overloaded ToString() method, in which I passed two parameters, namely a string ("N"), and the NumberFormatInfo class that I instantiated.

Hope this little code snippet helps!


Comments:
Thanks a lotta dude ;) Am using SharpDevelop 3.0 Beta 1 and your example help a lot, make more such "simple" tutorials, i'll appreciate it as many others who 're joining into c#, i guess !
 
Post a Comment



<< Home