BeginnerLesson 2 of 204 min read

Variables and Types: int, long, double and decimal for Money

Learn C# value types and their ranges, how checked arithmetic catches overflow, why double cannot hold 0.1 exactly and how decimal fixes that for money, verified by an independent calculation.

In this lesson you will

  • Declare variables and use var
  • Know the ranges of int and long
  • Use checked arithmetic
  • Use decimal for money

About 28 minutes

The cart’s takings are off by a fraction

Omar adds up the price of each drink as a double, and at the end of the day his program says that he took 45.09999999999999 euro. The customers paid 45.10. Floating point numbers cannot store most decimal fractions exactly, and for money C# offers a better type, decimal. Before that, the main types and their limits are worth learning, since every calculation depends on them.

Type Size Holds
int 32 bits Whole numbers from -2,147,483,648 to 2,147,483,647
long 64 bits Whole numbers up to about 9.2 quintillion
double 64 bits Decimals with about 15 digits of precision, stored in binary
decimal 128 bits Decimals with 28 to 29 digits, stored in decimal, made for money
bool 1 bit of meaning true or false
char 16 bits One UTF-16 character
string Reference type Text, immutable

A variable has a type, and you can let the compiler infer it with var when the value on the right makes it obvious, as in var cups = 12. C# checks types when it compiles. Number literals have suffixes: 12L is a long, 1.5m is a decimal, and 1.5f a float. By default, integer arithmetic that goes past the range wraps around silently. Writing checked(…) around an expression, or using a checked block, makes it throw an OverflowException instead.

Console.WriteLine($"int range: {int.MinValue} to {int.MaxValue}");
Console.WriteLine($"long max: {long.MaxValue}");
int top = int.MaxValue;
int wrapped = unchecked(top + 1);
Console.WriteLine($"int.MaxValue + 1 (unchecked) = {wrapped}");
try { int boom = checked(top + 1); Console.WriteLine(boom); }
catch (OverflowException) { Console.WriteLine("checked arithmetic threw OverflowException"); }
Console.WriteLine($"as long: {(long)top + 1}");
double d = 0.1 + 0.2;
decimal m = 0.1m + 0.2m;
Console.WriteLine($"double 0.1 + 0.2 = {d:R}, equal to 0.3? {d == 0.3}");
Console.WriteLine($"decimal 0.1 + 0.2 = {m}, equal to 0.3? {m == 0.3m}");
double dsum = 0; decimal msum = 0;
for (int i = 0; i < 10; i++) { dsum += 4.51; msum += 4.51m; }
Console.WriteLine($"ten drinks at 4.51: double {dsum:R}, decimal {msum}");
var cups = 12;
Console.WriteLine($"var infers: {cups.GetType().Name}, {(1.5m).GetType().Name}, {(2L).GetType().Name}");
int range: -2147483648 to 2147483647
long max: 9223372036854775807
int.MaxValue + 1 (unchecked) = -2147483648
checked arithmetic threw OverflowException
as long: 2147483648
double 0.1 + 0.2 = 0.30000000000000004, equal to 0.3? False
decimal 0.1 + 0.2 = 0.3, equal to 0.3? True
ten drinks at 4.51: double 45.09999999999999, decimal 45.10
var infers: Int32, Decimal, Int64

Adding one to the largest int wrapped to -2,147,483,648 when unchecked, and with checked the program threw an OverflowException, which is what you want when a wrong number is worse than a stopped program. As a long the true value is 2,147,483,648. For the decimals, double gave 0.1 + 0.2 = 0.30000000000000004, which is not equal to 0.3, while decimal gave exactly 0.3.

Omar’s problem shows in the loop. Ten drinks at 4.51 euro add up to 45.09999999999999 as a double, which has a tail of binary rounding noise, and exactly 45.10 as a decimal. A decimal stores digits in base ten, so the amounts that people write with a decimal point are stored exactly, and it is the right type for prices and accounts. It is slower than double and has a smaller range, so use double for measurements and calculations in science and graphics, and decimal for money.

Check by hand: ten times 4.51 is 45.10. An independent Python calculation agrees in both worlds: Python’s decimal module gives 45.10, and its ordinary float sum gives 45.09999999999999, the same noisy number that the C# double produced, because both follow the same IEEE 754 standard for double precision numbers.

Where each type belongs

A simple rule helps: use int for counts and indexes, long when a number may pass two billion, double for measurements and scientific work, and decimal for money and anything a person writes with a decimal point and expects to add up exactly. Choosing the right type at the start avoids a whole family of bugs, because the type decides both the range of values and how rounding behaves, and the compiler will then refuse to mix them by accident without an explicit conversion.

Never use double for money

Rounding noise accumulates and equality tests fail. Use decimal, or keep whole cents in a long.

Use checked where a wrong answer is worse than a crash

Wrap important arithmetic in checked, or turn on checked arithmetic for the whole project with a compiler setting, and test the boundaries.

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.

Practice

Add up a list of ten prices as double and as decimal and print both. Find the largest value of byte and short using their MaxValue constants. Try checked and unchecked on a byte that you increase beyond 255.

Check what you learned

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

Which type is made for money?

  1. double
  2. float
  3. decimal
  4. char

It stores base ten digits.

What does checked(a + b) do on overflow?

  1. Wraps silently
  2. Throws OverflowException
  3. Returns zero
  4. Ignores b

unchecked wraps.

Why is 0.1 + 0.2 not 0.3 as a double?

  1. C# has a bug
  2. Binary cannot store 0.1 exactly
  3. Addition is wrong
  4. The numbers are too big

The same happens in most languages.

What does var do?

  1. Lets the compiler infer the type
  2. Makes a variable dynamic
  3. Creates a constant
  4. Hides a variable

The type is still fixed at compile time.

What is the suffix for a decimal literal?

  1. m
  2. d
  3. f
  4. L

1.5m is a decimal.

Summary

  • int and long are exact whole numbers with silent wrap-around unless checked.
  • double is binary and approximate; decimal is exact for base ten fractions.
  • Use decimal for money.
  • var infers the type at compile time.

Next lesson

Lesson 3 covers operators and strings, including interpolation and formatting.

Questions

What is the difference between value and reference types?

Value types such as int hold the value directly. Reference types such as string hold a reference to an object on the heap.

When should I use float?

Rarely. It is used where memory matters, such as large arrays in graphics. Prefer double for general calculations.

What is a nullable type?

A value type that can also be null, written with a question mark, as in int?. Lesson 17 returns to nullability.

Progress is saved in this browser.