== 在 C# 中的浮点数和小数点之间

== between float and decimal in C#

static void Main()
{
     int a=10;
     Console.WriteLine(Convert.ToSingle(a)==Convert.ToDecimal(a));
}

为什么这段代码会抛出错误

== cannot be applied to operands of type float and decimal

即使两个转换语句 return 10?

如下图

bool Compare<T>(T x, T y) where T : class
{
    ...
}

所以xy应该是相同的数据类型。那么只有它可以比较。十进制是128位,单进制是32位。

十进制为Decimal floating point and Double is Binary floating point

还有 Convert.ToSingle(): 大小 - 4 字节 精度-7位

decimal.ToSingle(): 大小 - 16 字节 精度 -28-29 位小数

尽管它们在显示时可能会给出相同的输出。 在内部他们是不一样的。

float 和 double 是 floating binary point types where as decimal is floating decimal point type

有趣的文章https://zetcode.com/lang/csharp/datatypes/

ToSingle() 表示浮点数,ToDecimal() 表示双精度值,这就是精度匹配的原因