1. Fractions
Let's remember our project — say, it's a super simple calculator. Or any program where you need calculations (from basic money counting to hardcore physics). Not everything in real life is a whole number, and that's just how it is!
So let's grab a new data type!
In programming, fractional numbers are also called real numbers, or floating-point numbers (floating-point). In C#, like in most languages, you need them to store not just whole numbers, but also "fractional" values: stuff like 3.14, -28.57, 2.718281828...
There are two main types of real numbers:
| Type | Stores | Value Range (approx.) | Precision | Typical Size |
|---|---|---|---|---|
|
Numbers | ±1.5 × 10-45 ... ±3.4 × 1038 | ~7 digits after the decimal | 4 bytes |
|
Numbers | ±5.0 × 10-324 ... ±1.7 × 10308 | ~15-16 digits after the decimal | 8 bytes |
The float Type
The float type got its name from floating-point number. Real numbers are math numbers, they have certain properties. But computers have a lot of limitations. So it's not totally correct to call fractional numbers in C# "real numbers". For them, we use the name "floating-point numbers".
The float type usually stores 7 significant digits (like 0.1234567), a power of ten, and takes up 4 bytes in memory. That's not much for precise calculations, so everyone quickly switched to double precision numbers.
2. Declaring and Initializing double Variables
It's just like with int — only now we use double.
// Declare a variable and assign it the value of Pi
double pi = 3.1415926;
// You can declare without initializing too
double averageSalary;
averageSalary = 91234.56;
// You can do math!
double pizzaPieces = 8;
double friends = 3;
double piecesPerFriend = pizzaPieces / friends; // 2.666... (not 2)
Syntax Features:
- Use a dot (3.14) as the decimal separator. If you use a comma, you'll get a compile error!
- Technically, if you write double d = 3;, you won't get an error — types are auto-converted (an integer turns into a "real" number with no loss).
3. Input and Output of Real Numbers with Console
Let's try printing a fractional number:
double amount = 42.75;
Console.WriteLine(amount); // Prints: 42.75
All good! What if we add some text:
Console.WriteLine("Your balance: " + amount + " euro."); // Your balance: 42.75 euro.
Input from Keyboard
The main catch: Console.ReadLine() always returns a string, so you need to convert it to double.
Console.WriteLine("Enter the temperature outside:");
string input = Console.ReadLine();
double temperature = double.Parse(input); // Convert string to double
Console.WriteLine("It's currently: " + temperature + " degrees outside.");
4. The double Type in Action: Arithmetic
All the usual operations (+, -, *, /) work just like for int:
double distance = 100.5;
double time = 2.0;
double speed = distance / time; // 50.25
Console.WriteLine("Average speed: " + speed); // Average speed: 50.25
That's all the arithmetic. The only difference: the result of division is always a fractional number if at least one operand is double.
Compare with int
int a = 5, b = 2;
Console.WriteLine(a / b); // 2 (remainder is dropped)
double aa = 5, bb = 2;
Console.WriteLine(aa / bb); // 2.5
5. Typical Mistakes and Weird Stuff When Working with double
String Conversion Error
Classic situation: user enters 3,14 — but the program expects 3.14.
// This will throw an error if you enter "3,14"
double value = double.Parse(Console.ReadLine());
If you're working with the program in countries where a "comma" is the separator for whole and fractional parts (like Poland, Germany), then double.Parse works fine. But if the app is running with "English" settings, expect a dot.
The "Inaccuracy" Error of Numbers in a Computer
Here's where newbies usually get a bit confused:
double x = 0.1 + 0.2;
Console.WriteLine(x); // Huh... 0.30000000000000004
Congrats, you've hit the "magic" of how fractional numbers are represented inside a computer. The thing is, a lot of numbers can't be represented exactly in binary. We'll talk more about this in the next lecture, for now — don't panic! It's usually not a big deal for most apps, but there are quirks in finance and the hard sciences.
6. Important: double and int — Automatic and Explicit Conversion
Sometimes you add an integer and a fraction, or assign an int to a double variable — no errors:
int i = 2;
double d = i; // All good!
Console.WriteLine(d); // 2
double dd = 3.7;
int ii = (int) dd; // You need to explicitly cast double to int!
Console.WriteLine(ii); // 3, fractional part is dropped
This often surprises people — why did the fractional part disappear after casting? It's just because the int type can't store fractions (everything after the dot is gone forever).
More about converting double to int and the (int) operator in the next lecture.
7. Formatted Output: Making double Look Good
Often by default, double prints with a bunch of extra zeros. You can format the output:
double temp = 23.56789;
Console.WriteLine(temp); // 23.56789
Console.WriteLine(temp.ToString("F2")); // 23.57 (2 digits after the decimal)
Console.WriteLine($"{temp:F1}"); // 23.6 (string interpolation)
| Format | Result | Description |
|---|---|---|
| "F0" | 24 | No decimal part |
| "F2" | 23.57 | Two digits after the decimal |
| "F5" | 23.56789 | Five digits after the decimal |
GO TO FULL VERSION