decimal
类型的范围较小,但精度高于 double
。 “固定点”一词意味着,十进制小数点(或二进制小数点)不会移动。
decimal min = decimal.MinValue;
decimal max = decimal.MaxValue;
Console.WriteLine($"The range of the decimal type is {min} to {max}");
输出
The range of the decimal type is -79228162514264337593543950335 to 79228162514264337593543950335
十进制类型的精度更高:
double a = 1.0;
double b = 3.0;
Console.WriteLine(a / b);
decimal c = 1.0M;
decimal d = 3.0M;
Console.WriteLine(c / d);
输出
0.333333333333333 0.3333333333333333333333333333
数字中的 M
后缀指明了常数应如何使用 decimal
类型。
可以看到,使用十进制类型执行数学运算时,十进制小数点右侧的数字更多。
double r = 2.50;
Console.WriteLine(r * r * Math.PI);
输出
19.6349540849362