C# Decimal Examples

Value Decimal

Decimal type

The decimal type stores numeric data accurately. The .NET Framework offers this type for programs where rounding errors are harmful. Decimal stores large and small numbers with many digits after the decimal place. It provides useful static and instance methods.

Keywords

These C# examples show the decimal number type. Decimal stores important numbers with many digits.

Operators

The decimal type is a value type, and it can be manipulated with the standard numeric operators in the C# language. These operators include + - * and /. As shown in this program, you can also test decimal values with the equality operator == and print decimals to the Console.

Program that uses decimal operators [C#]

using System;

class Program
{
    static void Main()
    {
	decimal d = 1.0M;
	// Test decimal.
	if (d == 1.0M)
	{
	    Console.WriteLine(d);
	}
	decimal y = 0.5M;
	// Add decimal.
	y += d;
	Console.WriteLine(y);
	// Subtract and multiply decimal.
	y -= (d * 2);
	Console.WriteLine(y);
    }
}

Output

1.0
1.5
-0.5

Constants

If you want to know the maximum or minimum value of the decimal type, there is no need to look this up or memorize it. You instead should access the MaxValue and MinValue constants, as shown in this program. Also, for clarity purposes you can use the One, Zero, and MinusOne constants. Using these constants may provide for more self-documenting code.

Program that reveals decimal constants [C#]

using System;

class Program
{
    static void Main()
    {
	Console.WriteLine(decimal.MaxValue);
	Console.WriteLine(decimal.MinValue);
	Console.WriteLine(decimal.One);
	Console.WriteLine(decimal.Zero);
	Console.WriteLine(decimal.MinusOne);
    }
}

Output

79228162514264337593543950335
-79228162514264337593543950335
1
0
-1

Floor and Ceiling

When using the decimal type, you should call methods available on the decimal class instead of those in the Math class for accuracy reasons. When you take the ceiling of 1.1, you get 2. When you take the floor of that same number, you receive 1. In other words, ceiling is the integer above the number and the floor is the integer below the number.

Math.Ceiling Usage Math.Floor Method
Program that uses Ceiling and Floor methods [C#]

using System;

class Program
{
    static void Main()
    {
	Console.WriteLine(decimal.Ceiling(1.1M));
	Console.WriteLine(decimal.Floor(1.1M));
    }
}

Output

2
1

Add, Multiply, Subtract and Divide

To improve the clarity of some of your decimal manipulations, you can use the Add, Multiply, Subtract and Divide methods directly in your code. Each of these methods receives two arguments. You can imagine the classic arithmetic operator in between the two arguments.

Program that uses math methods [C#]

using System;

class Program
{
    static void Main()
    {
	Console.WriteLine(decimal.Add(1.1M, 1.3M)); // Add
	Console.WriteLine(decimal.Multiply(5.0M, 2.0M)); // Five times two
	Console.WriteLine(decimal.Subtract(2.0M, 1.0M)); // Two minus one
	Console.WriteLine(decimal.Divide(10M, 2M)); // Ten divided by two
    }
}

Output

2.4
10.00
1.0
5

Remainder

When doing important computations with money, you may want to get the remainder of a division. The remainder is the part left over after the division completes. In this program, we show that the remainder of 2 divided by 1.5 is 0.5. This is because the 0.5 is left over after the division occurred.

Program that uses Remainder method [C#]

using System;

class Program
{
    static void Main()
    {
	// Remainder of 2 divided by 1.5 is 0.5
	Console.WriteLine(decimal.Remainder(2.0M, 1.5M));
    }
}

Output

0.5

Truncate

Another useful method you can invoke on the decimal type is the Truncate method. This method simply erases all the numbers after the decimal place. It doesn't take into consideration whether the number would be rounded up or rounded down. This program shows that when you truncate 4.55, you get the number 4. This method returns an integer of type decimal.

Program that uses Truncate method [C#]

using System;

class Program
{
    static void Main()
    {
	// Truncate removes the digits after the decimal place.
	Console.WriteLine(decimal.Truncate(4.55M));
    }
}

Output

4

Negate

As you might guess, the Negate method on the decimal type makes positive decimals negative, and makes negative decimals positive. You could duplicate this functionality by multiplying by negative one, but this method is more self-documenting. For code that deals with money, you want clear and documented logic.

Program that uses Negate method [C#]

using System;

class Program
{
    static void Main()
    {
	// Makes positive numbers negative, and negative numbers positive.
	Console.WriteLine(decimal.Negate(1.5M));
	Console.WriteLine(decimal.Negate(-1.5M));
    }
}

Output

-1.5
1.5

Round and MidpointRounding

The Round method on the decimal type is useful for many programs. The decimal.Round method by default rounds down or up to the specified decimal place when you call it. You can specify the MidpointRounding enumerated constant to further define the required behavior. The ToEven value means that when a number needs to be rounded, it is always rounded to the nearest even number. The AwayFromZero value means that numbers are rounded up for positive numbers and down for negative numbers.

Program that uses decimal.Round method [C#]

using System;

class Program
{
    static void Main()
    {
	// Round to one decimal place.
	Console.WriteLine(decimal.Round(1.59M, 1));

	// Demonstrate MidpointRounding enumeration.
	Console.WriteLine(decimal.Round(2.5M, 0, MidpointRounding.ToEven));
	Console.WriteLine(decimal.Round(2.5M, 0, MidpointRounding.AwayFromZero));
    }
}

Output

1.6
2
3

Parse and TryParse

As with other numeric types in the C# language, the decimal type lets you convert from strings to actual decimals. The decimal.Parse method will throw an exception if you feed it an incorrectly formatted value. The decimal.TryParse method will handle errors by returning a false value. You should use Parse if you expect all input will be correct, and TryParse if you expect errors to be common.

TryParse Overview
Program that parses strings into decimals [C#]

using System;

class Program
{
    static void Main()
    {
	// Use Parse on arguments that are always correct.
	decimal value = decimal.Parse("100.01");
	Console.WriteLine(value);

	// Use TryParse when errors are expected.
	decimal value2;
	if (decimal.TryParse("perl", out value2))
	{
	    Console.WriteLine("Not reached");
	}
    }
}

Output

100.01

Convert from decimal

Conversion or change

Because the decimal type is 16 bytes, it is wasteful to store many decimals when you do not need that much accuracy. You can use the To* methods on the decimal type to convert to smaller memory representations of the number. These methods will throw exceptions if the conversion cannot be done because the decimal value is too large to be represented in the target type.

Program that converts from decimal type [C#]

using System;

class Program
{
    static void Main()
    {
	const decimal input = 5;
	// Convert this decimal into other compatible types.
	Console.WriteLine(decimal.ToByte(input));
	Console.WriteLine(decimal.ToDouble(input));
	Console.WriteLine(decimal.ToInt16(input));
	Console.WriteLine(decimal.ToInt32(input));
	Console.WriteLine(decimal.ToInt64(input));
	Console.WriteLine(decimal.ToSByte(input));
	Console.WriteLine(decimal.ToSingle(input));
	Console.WriteLine(decimal.ToUInt16(input));
	Console.WriteLine(decimal.ToUInt32(input));
	Console.WriteLine(decimal.ToUInt64(input));
    }
}

Output

5
5
5
5
5
5
5
5
5
5

FromOACurrency and ToOACurrency

Programming tip

The decimal type also provides the FromOACurrency and ToOACurrency methods. The FromOACurrency method receives an OA value and converts it into a decimal. The ToOACurrency takes a decimal and converts it into an OA value. OA values are a Microsoft-specific encoding and also can store dates. You should only use these methods if you are translating Excel spreadsheets or certain Microsoft database formats.

FromOADate and Excel Dates

Memory

Garbage collection visualization

How much memory does the decimal type use? As stated in this article, it requires 16 bytes. This site also contains a more detailed examination of the memory usage of the decimal type.

Decimal Memory

Summary

.NET Framework information

The decimal type in the C# language and .NET Framework is a powerful and accurate representation for number data in memory. With its large selection of static methods, the decimal type is valuable for representing important quantities like amounts of money.

Number Examples
.NET