C# Variables - Numbers

Number values are essential in almost every application. Whether it’s a payroll application that calculates salaries and distributes paychecks, a recipe tracking system that allows you to change the number of servings dynamically, or a video game that needs to know how many rocks are needed to build a variety of houses.



When using C#, there are two main types of numeric variables; integral and floating-point

Integral Numbers

An integral type represents a whole number, also known as an integer. Integers do not contain decimal points or fractions. The most common integral type used in C# is the System.Int32, which Visual Studio has given the alias of “int.”


An int can store any number from -2,147,483,648 to 2,147,483,648. If your application needs a number larger than that, you will need to use a long data type (System.Int64) who’s range is from +/- 9,223,372,036,854,775,808. Most applications don’t need numbers that large, which is why the int data type is more common.


Declaration and Initialization

You declare an integral type the same you declare the other variable types, with the type keyword and the variable name.

 int computerAge;
 int userAge;
 long planetAge;

Integer Literals

An integral variable can be initialized with a literal, similar to strings or characters. The main difference for numeric variables is that no quotes, single or double, are needed.

 int computerAge = 5;
 int userAge = 49;
 long planetAge = 4500000000;

It’s important to note that commas are not used when setting a numeric value to a variable. A comma is a character. If you use a character in an initialization, Visual Studio is expecting the value to be enclosed in quotes and set to a string variable.

Variable Assignment

Integral values can also be set by using another variable. However, the data type of both variables must be the same.

 int userAge = 49;
 long planetAge = 4500000000;
 string planetAgeString = "4,500,000,000";
 
 int newNumber = planetAge;
 int newNumber = planetAgeString;
 int newNumber = userAge;

In this example, the first two initializations of newNumber will cause problems since planetAge has a data type of “long” and planetAgeString has a data type of “string.” If you wanted to store either of those values into an integer variable, you would have to “explicitly” convert them. This topic is covered in a different blog post.


Calculation Results

Another way you can initialize an integral variable is by setting its value to the result of a calculation.

 int ageDifferenceUserComputer = userAge - computerAge;
 long ageDifferenceUserPlanet = planetAge - userAge;
 int ageDivisor = 0;
 int userAgeDivided = userAge / ageDivisor;

You need to take care of when assigning values with a calculation result. Visual Studio has no way of knowing whether or not that calculation is going to cause problems. It this code sample, userAgeDivided is going to cause a problem since it’s not possible to divide by Zero. The code will compile, but the application will crash with a DivideByZeroException being the cause.


Floating-point Numbers

A floating-point type represents a real number, meaning a number with a decimal point. The most common floating-point type used in C# is the System.Double, which Visual Studio has given the alias of “double.” The range of values for the double is +/- 1.7 × 10308. It has a precision of approximately 15 to 16 digits.


The other floating-point type is System.Single which has an alias “float.” A float has a precision of 7 to 9 digits. Its range of values is +/- 3.4 x 1038


What is Precision

Precision is the number of digits in a variable’s value. The higher the precision, the more numbers that the variable will hold.


A float has a precision of 7. This means that it can only hold seven numbers in the variable regardless of where the decimal point falls.


  • 34567.54

  • 89.45981

  • 977639.8

  • 4.956616

  • 8341469


A double has a precision of 15.


  • 34567.5458412589

  • 89.4598187259658

  • 977639.848574583

  • 4.95661678541268

  • 8341469.58974525


The extended precision of the double allows the value of the variable to hold more digits, which is why it is more commonly used.


The Decimal Type

The System.Decimal data type is a third floating-point type with a range of +/- 7.9228 x 1028. Although the decimal has a smaller range than a float, it takes up twice as much memory as a double.


The reason for this is that the decimal has a precision of 28 to 29 digits. This provides a higher level of numeric precision that is needed for financial and scientific calculations.

Declaration and Initialization

Floating-point variables are declared in the same way as the other data types you have learned.

 float moneyPerMinute;
 double minutesUntilNextBirtday;
 decimal moneyDueOnBirthday;

Literals

Literals are permitted when assigning values to floating-point variables. When assigning a value to a double, you just provide the value.

 double minutesUntilNextBirtday = 399454.2396;

However, an extra step is needed when assigning a value to a decimal or float. When assigning values to those data types, you have to provide a suffix so that Visual Studio knows to set the proper precision for the number. If you don’t provide a suffix, it will be treated as a double. For a float, use the suffix of "f". Use "m" for a decimal.

 float moneyPerMinute = 4.75f;
 decimal moneyDueOnBirthday = 1897407.6381m;

Variable And Calculation Assignment

You can initialize floating-point variables with other variables just as you can with integral variables. You can also set their value by using a calculation. The same rules and warnings apply to floating-point variables as integral values.

Numeric Data Type Methods

MinValue and MaxValue

Every numeric data type has two properties you can use in case you can’t remember the range of values that data type can hold. The MinValue and MaxValue properties will provide you with that information.


Console.WriteLine($"Int Min Value - {int.MaxValue} : Max Value {int.MaxValue}");
Console.WriteLine($"Long Min Value - {long.MaxValue} : Max Value {long.MaxValue}");
Console.WriteLine($"Float Min Value - {float.MaxValue} : Max Value {float.MaxValue}");
Console.WriteLine($"Double Min Value - {double.MaxValue} : Max Value {double.MaxValue}");
Console.WriteLine($"Decimal Min Value - {decimal.MaxValue} :Max Value {decimal.MaxValue}");

ToString()

Every numeric data type in C# has a method named ToString that will provide the text representation of the data being stored in the variable.

 int luckyNumber = 7;
 Console.WriteLine(luckyNumber.ToString() + " is my lucky number.");
 double wage = 14.50;
 Console.WriteLine("I make " + wage.ToString() + " dollars an hour.");

Parse() and TryParse()

Parse, and TryParse are two methods that exist for all numeric data types. These methods are used to aid in the conversion of value to that particular datatype.


Parse is covered in the blog regarding converting between types.


TryParse is covered in the blog covering conditional logic.

57 views0 comments

Recent Posts

See All