Beginner · Getting started with C# and .NET · topic 5 of 43 · 30 min
Operators, conversions and parsing input
Explanation
Arithmetic operators
| Operator | Meaning | Example | Result |
|---|---|---|---|
| + | add | 7 + 2 | 9 |
| - | subtract | 7 - 2 | 5 |
| * | multiply | 7 * 2 | 14 |
| / | divide | 7 / 2 | 3 (both ints!) |
| / | divide | 7 / 2.0 | 3.5 |
| % | remainder | 7 % 2 | 1 |
Integer division: the most common surprise
When both sides of / are whole-number types, C# does integer division: it keeps only the whole part and throws away the rest. This is useful (how many full boxes of 12 can I pack from 50 mangoes? 50 / 12 is 4) but it surprises people working out averages.
int total = 250;
int subjects = 3;
Console.WriteLine(total / subjects); // 83
Console.WriteLine(total % subjects); // 1
Console.WriteLine((double)total / subjects); // 83.33333333333333Shortcuts: ++, --, +=
int count = 5;
count++; // 6
count += 10; // 16
count -= 1; // 15
count *= 2; // 30
Console.WriteLine(count);Joining strings and numbers
If either side of + is a string, + joins (concatenates) instead of adding. C# works left to right, which can give surprises.
Console.WriteLine("Total: " + 5 + 3); // Total: 53
Console.WriteLine(5 + 3 + " items"); // 8 items
Console.WriteLine($"Total: {5 + 3}"); // Total: 8Implicit and explicit conversions
Converting is changing a value from one type to another. When no information can be lost, C# does it for you: this is an implicit conversion, for example int to long or int to double. When information might be lost, you must ask with a cast: put the target type in brackets. This is an explicit conversion.
int marks = 87;
double asDouble = marks; // implicit: 87
double price = 9.99;
int rupees = (int)price; // explicit cast: 9 (decimals cut off, not rounded)
Console.WriteLine(rupees);Parsing: turning text into numbers
Console.ReadLine always gives a string. "42" is text, not a number. To do maths you must parse it: read the text and build a number from it.
string input = "42";
int n = int.Parse(input); // 42
decimal amount = decimal.Parse("1299.50");
int bad = int.Parse("forty"); // crashes: FormatExceptionTryParse is the safe version. It returns true or false to say whether it worked, and gives the number through an out variable (explained in module 2). If parsing fails, the number is 0 and your program keeps running.
Console.Write("How many tickets? ");
string? text = Console.ReadLine();
if (int.TryParse(text, out int tickets))
{
Console.WriteLine($"Booking {tickets} tickets");
}
else
{
Console.WriteLine("Please type a whole number.");
}Rounding money correctly
Math.Round uses banker's rounding by default: a value exactly halfway goes to the nearest EVEN number. So Math.Round(2.5) is 2 and Math.Round(3.5) is 4. Bills usually round halves up, so say so explicitly.
Console.WriteLine(Math.Round(2.5)); // 2
Console.WriteLine(Math.Round(2.5, MidpointRounding.AwayFromZero)); // 3
Console.WriteLine(Math.Round(10.125m, 2, MidpointRounding.AwayFromZero)); // 10.13Overflow: when a number gets too big
An int can hold up to 2,147,483,647 (int.MaxValue). By default, going past it at run time does not crash; the number wraps around to a large negative value. This is called overflow. Wrap the code in checked to get an OverflowException instead.
int big = int.MaxValue;
big = big + 1;
Console.WriteLine(big); // -2147483648
checked
{
int x = int.MaxValue;
x = x + 1; // throws System.OverflowException
}Dividing by zero
Dividing an int by zero throws a DivideByZeroException. Dividing a double by zero does not crash; it gives infinity (or NaN, "not a number", for 0.0 / 0.0). Check the divisor first.
Need help?
Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.
Try:
Watch the lesson
Operators, conversions and parsing input · 1/7
In this lesson you will do arithmetic, convert between types, and safely turn typed text into numbers.
Prefer a video by a teacher? Find free videos on “C# integer division casting int.Parse TryParse tutorial” on YouTube ↗
In real life: A GST bill at a mobile shop
A mobile accessories shop in Hyderabad sells a charger for Rs 499. The billing app must add 18% GST, round to paise the way customers expect, and accept the quantity typed by the cashier without crashing on a typo.
decimal price = 499.00m;
const decimal GstRate = 0.18m;
Console.Write("Quantity: ");
if (!int.TryParse(Console.ReadLine(), out int qty) || qty <= 0)
{
Console.WriteLine("Invalid quantity");
return;
}
decimal subtotal = price * qty;
decimal gst = Math.Round(subtotal * GstRate, 2, MidpointRounding.AwayFromZero);
Console.WriteLine($"Subtotal: {subtotal:F2}");
Console.WriteLine($"GST 18%: {gst:F2}");
Console.WriteLine($"Total: {subtotal + gst:F2}");Practice (0/4 done)
What does Console.WriteLine(17 / 5); print?
What does Console.WriteLine("Rs " + 10 + 5); print?
int.TryParse("12a", out int n) returns what, and what is n?
Write a program that reads the marks of 3 subjects (each typed on its own line), rejects any input that is not a whole number, and prints the total and the average with 2 decimals. Example: 80, 75, 92 gives Total: 247, Average: 82.33.
Quick quiz
Read more (free)
Related help
Before this, learn
This topic builds on these. If something here feels new, open them first.
Related topics
- Installing .NET and using the dotnet CLIGetting started with C# and .NET · same module
- Type conversion and reading inputJava Programming (Core to Spring Boot) · Getting started with Java
- Type conversion and castingC Programming (from zero to systems) · Operators and control flow
- Numbers and mathsSQL and Databases · Functions, CASE and NULL
- Operators and expressionsJava Programming (Core to Spring Boot) · Getting started with Java
- Variables, types and constantsC++ Programming (modern C++ and DSA) · First steps: compiling, output, variables and input
Questions people ask about this
Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.
What is (int)7.9?
Answer: 7
A cast to int truncates (cuts off) the decimals. It does not round.
What does Math.Round(2.5) return in C#?
Answer: 2
By default C# uses banker's rounding: halfway values go to the nearest even number.
What happens with int.Parse("hello")?
Answer: Throws a FormatException
Parse throws when the text is not a number. Use TryParse to avoid the crash.
int x = int.MaxValue; x = x + 1; What is x (without checked)?
Answer: -2147483648
By default int arithmetic is unchecked and wraps around to the smallest int.
int a = 10, b = 4; double r = a / b; What is r?
Answer: 2
a / b is integer division (2) before the result is stored in the double, so r is 2.
What does 20 % 6 give?
Answer: 2
6 goes into 20 three times (18), leaving a remainder of 2.
Which conversion needs an explicit cast?Related
Answer: double to int
double to int may lose information (narrowing).
What is (int) 7.9?Related
What does CAST(9.99 AS INTEGER) return?Related
Answer: 9
CAST cuts off the fraction; it does not round. Use ROUND(9.99) for 10.
From Numbers and maths
What is 17 / 5 in Java with ints?Related
Pass the quiz (60% or more) or mark this topic as done when you are ready.
Your progress is saved on this device only.
Next steps
- This is the last topic of “Getting started with C# and .NET”. The module exam comes next.
- Module 1 exam: Getting started with C# and .NET · 13 questions · 20 min, without help. 5 topics of this module still to finish first.
- Then the next module, Decisions, loops and methods. 43 topics left in the course before the final exam.