In this example, a decimal and an int are mixed in the same expression. The result evaluates to the decimal type.
If you attempt to add the double and decimal variables by using a statement like this:
double x = 9;
Console.WriteLine(d + x); // Error
you will get the following error:
Operator '+' cannot be applied to operands of type 'double' and 'decimal'
// keyword_decimal.cs
// decimal conversion
using System;
public class TestDecimal
{
static void Main ()
{
decimal d = 9.1m;
int y = 3;
Console.WriteLine(d + y); // Result converted to decimal
}
}
Output
12.1
In this example, the output is formatted using the currency format string. Notice that x is rounded because the decimal places exceed $0.99. The variable y, which represents the maximum exact digits, is displayed exactly in the proper format.
// keyword_decimal2.cs
// Decimal type formatting
using System;
public class TestDecimalFormat
{
static void Main ()
{
decimal x = 0.999m;
decimal y = 9999999999999999999999999999m;
Console.WriteLine("My amount = {0:C}", x);
Console.WriteLine("Your amount = {0:C}", y);
}
}
Output
My amount = $1.00
Your amount = $9,999,999,999,999,999,999,999,999,999.00