在此例中,同一个表达式中混合使用了 decimal 和 int。计算结果为 decimal 类型。
如果试图使用下面这样的语句添加 double 和 decimal 变量:
double x = 9;
Console.WriteLine(d + x); // 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
}
} 输出
12.1
在此例中,输出用货币格式字符串格式化。注意:其中 x 被舍入,因为其小数点位置超出了 $0.99。而表示最大精确位数的变量 y 严格按照正确的格式显示。
// 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);
}
} 输出
My amount = $1.00
Your amount = $9,999,999,999,999,999,999,999,999,999.00