Skip to main content

Ints & Doubles

Not all numbers need decimals, so we have 2 different ways of creating them in C#.

Defining Numbers​

Integers (int) are whole numbers, such as:

int coolNum = 42;
int studentID = 1234567;
int negative = -4; // negatives are cool too

Doubles (double) are floating-point numbers that have a fractional part, such as:

double pi = 3.14159;
double cost = 20.95;
double tax = 2.99;

An int takes half the memory of a double (4 bytes vs 8 bytes). If you have millions of values and none of them need decimals, using int saves memory and is faster to process.

Adding numbers​

Be careful when adding numbers, different types take up different amounts of space

int sum = coolNum + 7; // int + int = int
double totalCost = cost + tax; // double + double = double

int cursed = coolNum + cost; // ❌ ERROR - can't implicitly narrow double to int
double lessCursed = coolNum + cost; // int widens to double automatically


double legal = coolNum + 7; // legal, int result widens to double

cursed fails and legal succeeds because:

  • int → double = widening (safe, implicit, allowed)
  • double → int = narrowing (stinky, loses info)

This is known as an "implicit conversion" where C# automatically converts one type to another. The compiler does it silently because it knows the conversion is safe. It stops you when it knows the conversion is unsafe.

References​

Bultena, Sandra and Youmna Badawy. "Integers & Floats." 420-SN1 Notes, John Abbott College, john-abbott-college.github.io/SN1-Notes/topics/04_variables/03_integers_floats/03_integers_floats.html