Chapter 3 Readings: 3.3 Numeric Data Types and Variables
Numeric Data Types and Variables
Variables of the string data type are used to store text, but they cannot store numeric data for the purpose of performing mathematical operations. To store numbers and perform mathematical calculations on them, a numeric data type must be used. C# provides several primitive data types for specialized and general purposes.
The three primary primitive numeric data types used for most general programming tasks are int, double, and decimal.
Primary Primitive Numeric Data Types
1. int Data Type
Description: Holds whole numbers (integers) only. Examples of valid
intvalues include , , and . Anintvariable cannot hold numbers with fractional parts, such as or .Primary Purpose: Primary data type for storing and working with whole numbers.
Memory Allocation: Uses bits of memory.
Value Range: through .
2. double Data Type
Description: Holds real numbers (numbers that may contain fractional parts), such as , , or .
Precision: Stored numbers are rounded to digits of precision.
Format: Stored in double precision floating-point notation.
Primary Purpose: Used for storing any real number that might have a fractional part, and particularly useful for extremely large or extremely small numbers.
Memory Allocation: Uses bits of memory.
Value Range: to (representing to ).
3. decimal Data Type
Description: Holds real numbers with significantly greater precision than the
doubledata type.Precision: Stored numbers are rounded to digits of precision.
Format: Stored in decimal notation.
Primary Purpose: Most commonly used in financial applications and for storing monetary amounts due to its high precision.
Memory Allocation: Uses bits of memory.
Value Range: to (representing to ).
Variable Declarations
Declaring a numeric variable requires specifying the data type followed by the variable name:
int speed;
double distance;
decimal grossPay;
int speed;declares anintvariable namedspeed.double distance;declares adoublevariable nameddistance.decimal grossPay;declares adecimalvariable namedgrossPay.
Numeric Literals
A literal is a piece of data written directly into a program's code. When a specific value is known at the time of writing code, it can be assigned as a literal to a variable. A numeric literal is a number written into the program's code.
Examples:
int hoursWorked = 40;
double temperature = 87.6;
In these statements, and are numeric literals.
Types of Numeric Literals
Integer Literals
When a numeric literal is written without a decimal point and fits within the range of an int ( to ), C# treats it as an int. This is referred to as an integer literal.
Examples:
int hoursWorked = 40;
int unitsSold = 650;
int score = -23;
Double Literals
When a numeric literal is written with a decimal point and fits within the range of a double, C# treats it as a double. This is referred to as a double literal.
Examples:
double distance = 28.75;
double speed = 87.3;
double temperature = -10.0;
Decimal Literals
To specify that a numeric literal is of the decimal data type, the letter M or m must be appended to the end of the literal.
Examples:
decimal payRate = 28.75m;
decimal price = 8.95M;
decimal profit = -50m;
Memory Tip: Remembering that "m" stands for "money" serves as a useful mnemonic that decimal literals must end with M or m.
Assignment Compatibility Rules
C# enforces strict assignment compatibility rules between different numeric data types to prevent unintentional data loss or range overflow errors.
Assignment Compatibility for int Variables
Allowed:
intvalues can be assigned tointvariables.Not Allowed:
doubleordecimalvalues cannot be assigned tointvariables.
Examples:
int hoursWorked = 40; // Valid: int assigned to int
int unitsSold = 650m; // ERROR: Cannot assign decimal to int
int score = -25.5; // ERROR: Cannot assign double to int
Reasons for Prohibition:
Fractional Data Loss:
doubleanddecimaldata types can store fractional values, whereasintvariables can only store whole numbers. Storing fractional values in anintwould require discarding the fractional portion.Range Overflow/Underflow:
doubleanddecimalvalues can represent numbers substantially larger or smaller than the allowed range of anintvariable ( to ).
Assignment Compatibility for double Variables
Allowed:
doubleorintvalues can be assigned todoublevariables.Not Allowed:
decimalvalues cannot be assigned todoublevariables.
Examples:
double distance = 28.75; // Valid: double assigned to double
double speed = 75; // Valid: int assigned to double (implicitly converted)
double sales = 6500.0m; // ERROR: Cannot assign decimal to double
Explanation:
Assigning an
intto adoubleis permitted because any value storable in anintcan be converted to adoublewith no loss of data. The implicit conversion happens automatically.Assigning a
decimalto adoubleis prohibited becausedecimalprovides up to digits of precision, whereasdoubleprovides only digits of precision. Converting adecimalto adoublecould result in precision loss.
Assignment Compatibility for decimal Variables
Allowed:
decimalorintvalues can be assigned todecimalvariables.Not Allowed:
doublevalues cannot be assigned todecimalvariables.
Examples:
decimal balance = 9280.73m; // Valid: decimal assigned to decimal
decimal price = 50; // Valid: int assigned to decimal (implicitly converted)
decimal sales = 6500.0; // ERROR: Cannot assign double to decimal
Explanation:
Assigning an
intto adecimalis permitted via implicit conversion without data loss.Assigning a
doubleto adecimalis prohibited because adoublevalue can potentially be much larger or smaller than the allowed range of adecimalvariable.
Explicit Type Conversion with Cast Operators
When an explicit conversion is required between non-compatible data types (such as assigning a double to an int), a cast operator can be used to override default compiler restrictions.
Syntax and Operation
A cast operator consists of the target data type name enclosed in parentheses (DataType) placed directly to the left of the expression or variable to be converted.
1 // Declare an int variable.
2 int wholeNumber;
3
4 // Declare a double variable.
5 double realNumber = 3.0;
6
7 // Assign the double to the int.
8 wholeNumber = (int)realNumber;
Line 2: Declares
wholeNumberas anint.Line 5: Declares
realNumberas adoubleinitialized with .Line 8: Uses the
(int)cast operator to convert the value ofrealNumberto anintand stores inwholeNumber.
Cast Operator Code Examples
Code Example | Description |
|---|---|
| The |
| The |
| The |
Truncation and Variable Immutability
Truncation: When converting a floating-point or decimal value containing a fractional part to an integer using a cast operator, any digits following the decimal point are completely dropped. This process is called truncation.
int wholeNumber;
double realNumber = 8.9;
wholeNumber = (int)realNumber;
After execution of this code, wholeNumber contains because the fractional component is dropped.
Immutability of Original Variables: Applying a cast operator to a variable does not alter the original variable's stored value. The operator merely extracts and converts the value for the expression. In the example above,
realNumberretains its original value of .
Declaring Local Variables with the var Keyword
C# allows local variables to be declared using the var keyword in place of an explicit data type name.
Type Inference Mechanism
When var is used, the compiler automatically infers the variable's data type based on the initialization value provided.
var amount = 100;
var interestRate = 12.0;
var stockCode = "D465U";
var accountBalance = 1000.0m;
amountis inferred asintbecause is an integer literal.interestRateis inferred asdoublebecause is a double literal.stockCodeis inferred asstringbecause"D465U"is a string literal.accountBalanceis inferred asdecimalbecause is a decimal literal.
Rules and Restrictions for var
Initialization Required: A variable declared with
varmust be initialized in the same statement so the compiler can infer its type.
var myvalue; // ERROR! Compiler cannot infer type without an initial value
```
2. **Single Variable Declarations Only:** Multiple variables cannot be declared in a single statement using `var`.
csharp var x, y, z = 99; // ERROR! Multiple variable declarations not permitted with var ```
Purpose of var
The var keyword is intended to simplify syntactically complex declaration statements and enhance overall code readability in advanced scenarios.
Checkpoint Review Questions and Answers
Checkpoint 3.14
Prompt: Specify the appropriate primitive numeric data type to use for each of the following values:
a. dollars
b. bananas
c. inches
d. cents
e. concert tickets
Answers:
a.
decimal(standard data type for monetary amounts) orint(for whole dollar amounts).b.
int(whole count of items).c.
double(real number containing a fractional part).d.
decimalorint(monetary units/cents).e.
int(whole count of items).
Checkpoint 3.15
Prompt: Which of the following variable declarations will cause an error? Why?
a.
decimal payRate = 24m;b.
int playerScore = 1340.5;c.
double boxWidth = 205.25;d.
string lastName = "Holm";
Answers:
Declaration b (
int playerScore = 1340.5;) will cause a compilation error.Reason: An
intvariable cannot accept adoubleliteral containing a fractional part () due to assignment compatibility rules and potential loss of data.
Checkpoint 3.16
Prompt: Write a programming statement that will convert the following decimal variable to an int and store the result in an int variable named dollars:
decimal deposit = 976.54m;
Answer:
int dollars = (int)deposit;
Checkpoint 3.17
Prompt: What value will the wholePieces variable contain after the following code executes?
double totalPieces = 6.5;
int wholePieces = (int)totalPieces;
Answer:
wholePieceswill contain the value . The fractional part () is truncated during explicit conversion toint.
Checkpoint 3.18
Prompt: Given the following declaration statements, what is the data type of each variable?
a.
var idNumber1 = "007";b.
var idNumber2 = 0.007;c.
var idNumber3 = 7;d.
var idNumber4 = 7m;
Answers:
a.
string(initialized with a double-quoted string literal"007").b.
double(initialized with a real number literal0.007).c.
int(initialized with an integer literal7).d.
decimal(initialized with a decimal literal7m).