8.0: Numbers

In this module we'll go more in depth on working with numbers in C#.

File Location

  1. Right click on the solution you made in the first module.

  2. Go to Add > New Project and select Console App (.NET Framework).

  3. Name it 08_numbers.

  4. Write your code for this module within Program.cs of that project.

Description

There are different variable types for numbers. You can use different types to more efficiently run your program. You will use different number types depending on the size and/or precision of the number. This will make your program more efficient.

Number Types Within C

Let's review the different number types in C#.

Type

Description

int i = 0;

A whole number with a size of 32 bits and range from -2,147,483,648 to 2,147,483,647. In the expression, we assign i to the integer 0.

short sh = 32767;

A whole number with size 16 bits and range from -32,768 to 32,767. In the expression we assign sh to 32767.

byte by = 255;

A whole number with size of 8 bits and range from 0 to 255. In the expression we assign by to 255.

long l = 7;

Long is an integer data type that can just hold more than a normal int type. Exactly 2 times more. The size is 64 bit and the range is -9223372036854775808 to 9223372036854775808. Another way to assign this type is Int64.

decimal p = 99.99999999999999999999999999;

A numeral that can go to a 128-bit precision decimal with a range of 28-29 decimal places. It's a very costly data type that takes a lot of energy for the program to run. A decimal data type is often used to represent money or other data that needs to be exact.

double d = 7.80000000000000;

A numeral that has a 15-16 digit precision with a 64-bit size.

float f = 10.8f;

Floating point integer, must put f explicit conversion afterwards. Float is similar to a double only it is stored as 32 bits within the memory.

decimal dd = 7.80m;

Without the suffix m, the number is treated as a double and generates a compiler error.

int? ni = null;

When there is a ? afterwards it means the value can be null. Null means it can either have a value there or it can be empty. Null can be used when you are not sure if there will be a value or not such as with web services or database results. Use .HasValue to see if the current Nullable object has a valid value of its underlying type.

Example:

Typically you will want to use doubles or decimals when dealing with money or numbers that need to be exact.

  1. In the first WriteLine you can see how many decimal places a double will go out to.

  2. In the second WriteLine we rounded our number to the second decimal place to make the percentage more readable to our user.

decimal Bill = 54.23;
decimal Tip = 12;

decimal Percentage = Tip / Bill;

Console.WriteLine(Percentage);
Console.WriteLine(Math.Round(Percentage, 2));
Console.ReadLine();

Last updated