Working with Variables: Numbers
Learn how to store numbers in C#, including whole numbers using decimal, binary, and hexadecimal notation.
Numbers are data on which we want to perform an arithmetic calculation, for example, multiplying. A telephone number is not a number. To decide whether a variable should be stored as a number or not, ask yourself whether you need to perform arithmetic operations on the number or whether the number includes non-digit characters such as parentheses or hyphens to format the number, such as .
In this case, the number is a sequence of characters, so it should be stored as a string
.
Storing numbers
Numbers can be natural numbers, such as 42, used for counting (also called whole numbers); they can also include negative numbers, such as -42 (called integers); or they can be real numbers, such as 3.9 (with a fractional part), which are called single-precision or double-precision floating-point numbers in computing. Let’s explore numbers:
Step 1: Use your preferred code editor to add a new "Console App/console project" named Numbers
to the Chapter02
workspace/solution
.
Select
Numbers
as the activeOmniSharp
project if you use Visual Studio Code. When the pop-up warning message says that required assets are missing, click "Yes" to add them.If you use Visual Studio 2022, set the startup project to the current selection.
Step 2: In Program.cs
, delete the existing code, and then type statements to declare some number of variables using various data types, as shown in the following code:
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <TargetFramework>net7.0</TargetFramework> <ImplicitUsings>enable</ImplicitUsings> <Nullable>enable</Nullable> </PropertyGroup> </Project>
Storing whole numbers
We might know that computers store everything as bits. The value of a bit is either 0 or 1. This is called a binary number system. Humans use a decimal number system. The decimal number system, also known as Base 10
, has ten as its base, meaning there are ten digits from 0 to 9.
Although it is the number base most used by human civilizations, other number base systems are popular in science, engineering, and computing. The binary number system, also known as Base 2
, has two as its base, meaning there are two digits, and ...