Decimal Literal in C#

When initializing variables in C#, you may have to specify the data type explicitly you intend it to be for numeric data types. If not, they will be treated as default data types like integers or doubles. It can cause compile-time errors if left out or errors during calculation.
The Decimal Literal
When initializing a decimal, you must do as presented below:
decimal decimalValue = 12.0M;
If you don’t add the decimal literal M
, the numeric value will be treated as a double and will cause errors. You can use both uppercase and lowercase notation. The reason why the decimal suffix is M
and not another letter like D
is because the double data type already took the letter D
.
Example:
using System;
namespace Literal_Example
{
class Program
{
static void Main(string[] args)
{
//Initialize the integer variable a
var decimalValue = 10.0M;
Console.WriteLine("First Variable: " + decimalValue.ToString() + "\nData Type: " + decimalValue.GetType().Name + "\n");
var floatValue = 10.0F;
Console.WriteLine("Second Variable: " + floatValue.ToString() + "\nData Type: " + floatValue.GetType().Name + "\n");
var doubleValue = 10.0;
Console.WriteLine("Third Variable: " + doubleValue.ToString() + "\nData Type: " + doubleValue.GetType().Name + "\n");
Console.ReadLine();
}
}
}
In the example above, we declared three different variables implicitly using var
, but each had a different suffix or none at all. You can observe how this changes the variable’s data type through the results printed to the console.
Output:
First Variable: 10.0
Data Type: Decimal
Second Variable: 10
Data Type: Single
Third Variable: 10
Data Type: Double