skip to content

In C#, what do the int expressions -1000 / 3 and -1000 % 3 evaluate to, and how do you keep the fraction?

level: juniorimportance: must knowfreq 72%

answer

  1. both operands int, so the result is int
  2. which way negatives are truncated
  3. remainder follows the left operand's sign
  4. convert before dividing, not after

basics

~20 s

With two int operands C# divides as integers and truncates toward zero: -1000 / 3 is -333 and -1000 % 3 is -1. Convert an operand to double or decimal before dividing to keep the fraction.

solid answer

~40 s

When both operands of `/` are integral, C# uses integer division, so the result is an `int` rounded toward zero: `1000 / 3` is `333` and `-1000 / 3` is `-333`, not `-334`. The remainder is defined as `a - (a / b) * b`, so a non-zero remainder takes the sign of the left operand: `-1000 % 3` is `-1` and `1000 % -3` is `1`. To get `333.33…`, convert one operand before the division, as in `(double)a / b` or `(decimal)a / b`; `(double)(a / b)` only converts a result that is already truncated, and so does assigning `a / b` to a `double` variable. `Math.DivRem` returns quotient and remainder together. An int divided by a zero int throws `DivideByZeroException`, while `double` division by zero yields infinity or NaN.

code

csharp · 20 lines
csharp
int invoiceCents = 1000, installments = 3;

Console.WriteLine(invoiceCents / installments);           // 333
Console.WriteLine(invoiceCents % installments);           // 1  (the cent left over)
Console.WriteLine(-invoiceCents / installments);          // -333  (toward zero, not -334)
Console.WriteLine(-invoiceCents % installments);          // -1  (sign of the left operand)
Console.WriteLine((double)invoiceCents / installments);   // 333.3333333333333
Console.WriteLine((double)(invoiceCents / installments)); // 333  (already truncated)
Console.WriteLine(Math.DivRem(-invoiceCents, installments)); // (-333, -1)

int noInstallments = 0;
try
{
    Console.WriteLine(invoiceCents / noInstallments);
}
catch (DivideByZeroException)
{
    Console.WriteLine("DivideByZeroException");
}
Console.WriteLine(double.IsPositiveInfinity(invoiceCents / 0.0)); // True: double division does not throw

go deeper

for a junior

Recall that two int operands give an int result truncated toward zero, that % keeps the sign of the left operand, and that you cast an operand before dividing to keep the fraction.

for a middle

Explain that the operand types choose the operator, not the target variable, and walk through why (double)(a / b) and double x = a / b both lose the fraction.

for a senior

Show where truncation and negative remainders bite in production: bucket indexes from negative hashes, installment splits that drop a cent, and int.MinValue / -1 throwing even when unchecked.

for a principal

Discuss when integer arithmetic on minor units is the safer design for money splits, and how the team documents who receives the leftover remainder.

## How C# picks the division operator C# has no single "divide" operation. The compiler chooses a predefined operator from the **types of the operands**, not from the variable that receives the result. If both operands are integral (`int`, `long`, and the smaller types, which are promoted to `int` first), it uses **integer division** and the result is an integer. If either operand is `float` or `double`, it uses floating-point division; if either is `decimal` (and the other is integral or `decimal`), it uses decimal division. That is why this line stores `3`, not `3.5`: ```csharp double half = 7 / 2; // 3: int division first, then the int 3 converts to double ``` The target type `double` plays no part in choosing the operator. The division finishes as `int` and only then is the result converted. When the two integral operands differ in width, the narrower one is converted first and the division happens in the wider type: an `int` divided by a `long` is a `long` division with a `long` result, still truncated. The same rules apply to the compound form, so `total /= count` with two `int` variables truncates exactly like `total = total / count`. ## Truncation toward zero Integer division in C# returns the quotient **rounded toward zero**. For positive operands that looks like rounding down, which is why people remember it as "floor". For negative operands the two differ: | Expression (int operands) | Result | Why | |---|---|---| | `1000 / 3` | `333` | 333.33… truncated toward zero | | `-1000 / 3` | `-333` | -333.33… truncated toward zero, not down to -334 | | `1000 % 3` | `1` | 1000 - 333 * 3 | | `-1000 % 3` | `-1` | -1000 - (-333) * 3 | | `1000 % -3` | `1` | the sign follows the left operand | ## The remainder operator and negative numbers For integers, C# defines `a % b` as `a - (a / b) * b`. Because `/` truncates toward zero, a non-zero remainder always has the **sign of the left operand**. So `%` is a remainder, not the mathematical modulo that is always non-negative: - `-1000 % 3` is `-1`, while a mathematical "-1000 mod 3" is `2`. - A bucket index computed as `hash % bucketCount` can be negative whenever `hash` is negative, and indexing an array with it throws `IndexOutOfRangeException`. - When you need a non-negative result, `((a % b) + b) % b` gives one for a positive `b`. - `Math.DivRem(a, b)` returns the truncated quotient and the matching remainder as a tuple, so `Math.DivRem(-1000, 3)` is `(-333, -1)`. ## Getting a fractional result To divide with a fraction, make one operand non-integral **before** the operator runs: 1. `(double)a / b`: the cast applies to `a`, so floating-point division is chosen; the result is a `double`. 2. `(decimal)a / b` or `a / (decimal)b`: decimal division, the right choice for money. 3. `a / 3.0` or `a / 3m`: a non-integral literal does the same job. The common bug is `(double)(a / b)`: the parentheses force the integer division first, so the cast receives an already truncated value. A rounding rule other than truncation (for example rounding up) needs either a different formula or a non-integral division followed by `Math.Ceiling` or `Math.Round`. ## Division by zero and the one overflow case - An `int` or `long` divided by a **variable** holding zero throws `DivideByZeroException` at run time, and so does `%`. - Dividing by a **constant** zero, such as `5 / 0`, does not compile: the compiler reports CS0020, "Division by constant zero". - A `double` divided by zero does not throw: `1.0 / 0.0` is positive infinity and `0.0 / 0.0` is NaN. A `decimal` divided by zero throws `DivideByZeroException`. - `int.MinValue / -1` cannot be represented as an `int`, and it throws `OverflowException` even in an unchecked context. ## Splitting an invoice into installments Integer division is often exactly what you want, as long as you handle the remainder on purpose. An invoice of 1,000 cents split into three installments is `1000 / 3 = 333` cents each with `1000 % 3 = 1` cent left over, which the code must add to one installment so the parts still sum to the total. A credit note of -1,000 cents gives `-333` and `-1`, so the same rule works for negative amounts only if the code expects a negative remainder.

  • What does int.MinValue / -1 do in C#, even inside an unchecked expression?
    It throws `OverflowException`, which derives from `ArithmeticException`. The true quotient, 2147483648, does not fit in an `int`, and unlike `+` or `*` there is no wrapped result to fall back on, so the runtime throws regardless of the checked or unchecked context. `int.MinValue % -1` throws the same way, so code that divides by a caller-supplied value should not assume that unchecked means no exception.
  • How do you round an int quotient up, for example the number of pages for 1000 rows at 30 rows per page?
    For non-negative operands, `(rows + perPage - 1) / perPage` stays in integer arithmetic and gives the ceiling: `(1000 + 29) / 30` is `34`. The addition can overflow when `rows` is close to `int.MaxValue`, so an alternative is `var (q, r) = Math.DivRem(rows, perPage);` followed by `q + (r > 0 ? 1 : 0)`.

  • -1000 / 3 is -334 because integer division rounds down.
  • The % operator in C# always returns a non-negative result.
  • (double)(a / b) gives the exact fractional quotient.
  • double share = 1000 / 3; stores 333.33 because the target is double.
  • Dividing an int by zero returns infinity instead of throwing.