BeginnerLesson 3 of 204 min read

Operators and Strings: Division, Interpolation and Formatting

Learn arithmetic and comparison operators, integer division and remainders, string methods, immutability, StringBuilder, formatting numbers and raw string literals, with results checked independently.

In this lesson you will

  • Predict integer division and remainder
  • Use string methods and interpolation
  • Format numbers and dates
  • Build text efficiently

About 28 minutes

Splitting the bill

Omar splits a 100 euro group order between 3 friends. The program says 33 each, and the missing euro puzzles him. As in most languages, dividing two ints in C# gives an int and drops the fraction. The remainder operator % gives what is left. For negative numbers the sign of the remainder follows the first number, so -7 % 3 is -1.

Operator Meaning Example
+ – * / Arithmetic 7 / 2 is 3 for ints
% Remainder 7 % 2 is 1
== != Equality cups == 12
< >= Comparison cups >= 10
&& || ! And, or, not open && !closed
?? Use a fallback if null name ?? “guest”

A C# string is immutable, so methods such as ToUpper and Replace return a new string. Concatenating in a long loop creates many temporary strings, and StringBuilder avoids that. Interpolated strings accept format specifiers after a colon: {price:F2} prints two decimals, {n:N0} adds thousands separators, and {x,8} pads to a width. Formatting uses the current culture, which can change the decimal separator, so programs that must produce the same text everywhere pass CultureInfo.InvariantCulture, and this course runs with the invariant culture to keep outputs the same. Raw string literals, written with three double quotes, let you include quotes and line breaks without escapes.

using System.Text;
Console.WriteLine($"100 / 3 = {100 / 3}, 100 % 3 = {100 % 3}, 100.0 / 3 = {100.0 / 3:F4}");
Console.WriteLine($"-7 / 2 = {-7 / 2}, -7 % 3 = {-7 % 3}");
string name = "Omar's Cart";
Console.WriteLine($"{name.ToUpper()} has {name.Length} characters; contains 'Cart': {name.Contains("Cart")}; index of 's': {name.IndexOf('s')}");
Console.WriteLine($"{name[..5]}|{name.Replace("Cart", "Cafe")}|{name.Substring(6)}");
var sb = new StringBuilder();
for (int i = 1; i <= 5; i++) sb.Append(i).Append(i < 5 ? "," : "");
Console.WriteLine($"built: {sb} ({sb.Length} chars)");
double price = 1234.5;
Console.WriteLine($"price: {price:F2} | {price:N0} | [{price,12:F1}] | [{price,-12:F1}]");
string text = """
    Menu: "flat white" 3.20
    Menu: "tea" 2.10
    """;
Console.WriteLine(text);
string maybe = null;
Console.WriteLine($"fallback: {maybe ?? "no name"}, same text? {("abc" == "ab" + "c")}");
Program.cs(17,16): warning CS8600: Converting null literal or possible null value to non-nullable type. [app.csproj]
100 / 3 = 33, 100 % 3 = 1, 100.0 / 3 = 33.3333
-7 / 2 = -3, -7 % 3 = -1
OMAR'S CART has 11 characters; contains 'Cart': True; index of 's': 5
Omar'|Omar's Cafe| Cart
built: 1,2,3,4,5 (9 chars)
price: 1234.50 | 1,234 | [      1234.5] | [1234.5      ]
Menu: "flat white" 3.20
Menu: "tea" 2.10
fallback: no name, same text? True

Dividing 100 by 3 as ints gave 33 with a remainder of 1: 3 x 33 + 1 = 100, so the missing euro is the remainder. With a decimal point the result is 33.3333. Division truncates towards zero, so -7 / 2 is -3 and -7 % 3 is -1.

The string “Omar’s Cart” has 11 characters, and the first s is at index 5, because indexes start at zero. The range syntax name[..5] took the first five characters. The StringBuilder made “1,2,3,4,5” in 9 characters without creating a string for each step. The format specifiers turned 1234.5 into 1234.50 with F2 and 1,234 with N0, which rounds to a whole number and adds a thousands separator. Note that the exact half went to the even neighbour, 1,234, and not up to 1,235, because current .NET versions round exact halves to even when formatting, so check the documentation before you rely on rounding in output. The comma with a width pads the field so that columns line up, with a minus sign for left alignment. The raw string literal kept its quotes and line breaks and removed the shared indentation, and the ?? operator supplied a fallback for a null string. The very first line of the output is not program output but a compiler warning, CS8600, about assigning null to a string that is not declared as nullable. It is the compiler pointing at a possible null mistake, and lesson 17 explains nullable reference types.

Check by hand: 3 x 33 = 99, so the remainder is 1. The text “Omar’s Cart” is O-m-a-r-‘-s, a space, C-a-r-t, which is 6 + 1 + 4 = 11 characters, and the s is the sixth character, at index 5. Python gives -4 and 2 for -7 // 2 and -7 % 3, because it rounds down, and C# truncates, which is why C# gives -3 and -1.

Integer division drops the fraction

If you want a decimal result, make one operand a double or decimal first, for example 100m / 3.

Use InvariantCulture when text must be identical everywhere

Formatting numbers and dates depends on the user’s culture. For files and data exchange, pass CultureInfo.InvariantCulture.

About this course

Every program in this lesson was built and run with the .NET 8 SDK and C# 12 while the course was written. .NET and C# release every year, so check the official Microsoft documentation for the current version and for features added after .NET 8. Raw string literals need C# 11 or later.

Practice

Split 250 euro among 7 friends with int division, the remainder, and decimal. Print the menu from a raw string literal with prices aligned in columns. Reverse a string using StringBuilder or by converting it to a char array.

Check what you learned

Five quick questions. Pick an answer and you will see straight away whether it is right and why.

What is 100 / 3 with two ints?

  1. 33.33
  2. 34
  3. 3
  4. 33

The fraction is dropped.

What is -7 % 3 in C#?

  1. 2
  2. 1
  3. -1
  4. -2

The sign follows the first operand.

What does {price:F2} do?

  1. Multiplies by two
  2. Adds two
  3. Formats the number with two decimals
  4. Prints twice

A format specifier.

Why use StringBuilder in a loop?

  1. It encrypts text
  2. It avoids many temporary strings
  3. It sorts text
  4. It is required

Strings are immutable.

What does ?? do?

  1. Compares two numbers
  2. Supplies a fallback when the left side is null
  3. Divides
  4. Loops

The null-coalescing operator.

Summary

  • Integer division truncates and % keeps the sign of the first operand.
  • Interpolated strings take format specifiers.
  • Strings are immutable; use StringBuilder for loops.
  • ?? supplies a fallback for null.

Next lesson

Lesson 4 covers decisions and loops, including switch expressions and pattern matching.

Questions

Is == on strings safe in C#?

Yes. Unlike some languages, C# compares the characters for strings with ==.

What does immutable mean?

The object cannot change after it is created. Methods return new strings.

How do I escape a quote in a normal string?

Use a backslash, as in \", or use a raw string literal.

Progress is saved in this browser.