Chapter 5 — Numbers

SAMS CSHARP 4.0 (Page 94)

Decide between Float, Double and Decimal

Money or finances – use decimal types.

Use Enormous Integers (BigInteger)

BigInteger class is in System.Numerics namespace. Need to add a reference before you can use it.

Format Numbers in a String

Group Digits – N

int number = 12345;
Console.WriteLine(number.ToString(“N“, CultureInfo.InvariantCulture));

You get

Print Leading 0

int number = 12345;
Console.WriteLine(number.ToString(“D8“, CultureInfo.InvariantCulture));

And here’s the output: (total 8 digits)

Specifiy number of decimal places

double number = 12345.6789;
Console.WriteLine(number.ToString(“F3“, CultureInfo.InvariantCulture));

The output is as follows (note the rounding):

Convert a string to a Number

parse a string into a number

Use (1) Parse (willhave exception) or (2) Tryparse (better)

string goodStr = ” -100,000,000.567 “;
double goodVal = 0;
// with C# you need to have “out” keyword
if (double.TryParse(goodStr, out goodVal)){
Console.WriteLine(“Parsed {0} to number {1}”, goodStr, goodVal);

Convert Between Number Bases

base 10 to base 2/8/16

Convert 100 (base-10) to a number that is base-16

Convert.ToString(100, 16)

Generate GUID

Guid g = Guid.NewGuid().

Post a comment or leave a trackback: Trackback URL.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: