Skip to content

Beginner · Getting started with C# and .NET · topic 5 of 43 · 30 min

Operators, conversions and parsing input

Explanation

Arithmetic in C# uses + - * / and %, but dividing two ints throws away the fraction: 7 / 2 is 3. To turn typed text into a number use int.Parse, or better int.TryParse, which does not crash on bad input. A cast like (int)9.7 cuts off the decimals, and an int that goes past its limit silently wraps around unless you use checked.

Arithmetic operators

OperatorMeaningExampleResult
+add7 + 29
-subtract7 - 25
*multiply7 * 214
/divide7 / 23 (both ints!)
/divide7 / 2.03.5
%remainder7 % 21

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.

csharp
int total = 250;
int subjects = 3;
Console.WriteLine(total / subjects);            // 83
Console.WriteLine(total % subjects);            // 1
Console.WriteLine((double)total / subjects);    // 83.33333333333333
Make one side a double (or decimal) to get the fraction.
Careful: double avg = total / subjects; still gives 83, not 83.33. The division happens first, with ints, and only the answer is stored in a double. Cast before you divide.

Shortcuts: ++, --, +=

csharp
int count = 5;
count++;        // 6
count += 10;    // 16
count -= 1;     // 15
count *= 2;     // 30
Console.WriteLine(count);
Shows 30. x += 10 means x = x + 10.

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.

csharp
Console.WriteLine("Total: " + 5 + 3);    // Total: 53
Console.WriteLine(5 + 3 + " items");      // 8 items
Console.WriteLine($"Total: {5 + 3}");     // Total: 8
Interpolation with { } avoids the confusion.

Implicit 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.

csharp
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);
A cast from double to int truncates: it drops everything after the point.

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.

csharp
string input = "42";
int n = int.Parse(input);           // 42
decimal amount = decimal.Parse("1299.50");
int bad = int.Parse("forty");       // crashes: FormatException
Parse crashes the program when the text is not a valid number.

TryParse 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.

csharp
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.");
}
Always prefer TryParse for anything a user types.

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.

csharp
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.13
Pass MidpointRounding.AwayFromZero for the school-style rounding most bills expect.

Overflow: 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.

csharp
int big = int.MaxValue;
big = big + 1;
Console.WriteLine(big);          // -2147483648

checked
{
    int x = int.MaxValue;
    x = x + 1;                   // throws System.OverflowException
}
Use long, or checked, when values can grow large, such as total sales across all stores.

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.

Tip: Formatting numbers: $"{price:F2}" always shows two decimals (499.00), and $"{count:N0}" adds thousands separators. The separators and decimal point follow the computer's culture settings, so a German computer shows 499,00.

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

Operators and conversions

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.

csharp
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}");
For quantity 2: Subtotal: 998.00, GST 18%: 179.64, Total: 1177.64.

Practice (0/4 done)

Task 1 · Question

What does Console.WriteLine(17 / 5); print?

Task 2 · Question

What does Console.WriteLine("Rs " + 10 + 5); print?

Task 3 · Question

int.TryParse("12a", out int n) returns what, and what is n?

Task 4 · Practice

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

Question 1

1.What is (int)7.9?

Question 2

2.What does Math.Round(2.5) return in C#?

Question 3

3.What happens with int.Parse("hello")?

Question 4

4.int x = int.MaxValue; x = x + 1; What is x (without checked)?

Question 5

5.int a = 10, b = 4; double r = a / b; What is r?

Question 6

6.What does 20 % 6 give?

Read more (free)

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).

From Type conversion and reading input

What is (int) 7.9?Related

Answer: 7

Conversion to int truncates.

From Type conversion and casting

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

Answer: 3

Integer division drops the decimal part.

From Operators and expressions

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

  1. This is the last topic of “Getting started with C# and .NET”. The module exam comes next.
  2. Module 1 exam: Getting started with C# and .NET · 13 questions · 20 min, without help. 5 topics of this module still to finish first.
  3. Then the next module, Decisions, loops and methods. 43 topics left in the course before the final exam.

← Previous: Types and variables