将 double 转换为 long 更改值

Cast double to long change the value

我注意到从 doublelong 的转换改变了值 当要转换的数字是 large,即使它远低于 long最大值。 例如,有人可以解释为什么这个转换 没有按预期工作 :

Convert.ToInt64(600000000000040000d)
// Return => 600000000000039936
Convert.ToInt64(600000000000040000L)
// Return => 600000000000040000

这给我的公式带来了一些麻烦... 谢谢

希望对您有所帮助:

When you convert a double or float value to an integral type, this value is rounded towards zero to the nearest integral value. If the resulting integral value is outside the range of the destination type, the result depends on the overflow checking context. In a checked context, an OverflowException is thrown, while in an unchecked context, the result is an unspecified value of the destination type.

来源:https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/explicit-numeric-conversions-table

注:Long是整型,是Int64:In C# What's the difference between Int64 and long?

另外,float 和 double 是带有浮点数的类型。它们以不同的方式存储在内存中 How are floating point numbers stored in memory?

维基百科:https://en.wikipedia.org/wiki/Single-precision_floating-point_format

好吧,double 尾数 52 只有 (参见 https://en.wikipedia.org/wiki/Double-precision_floating-point_format细节);这就是为什么 double 可以表示 精确的 整数值,直到 2**53 - 1 == 9007199254740991。然而,

 600000000000040000 > 9007199254740991

这就是为什么 舍入误差 不可避免的原因:

  double d = 600000000000040000d;

  long l = (long)d;

  double d2 = l;

  Console.WriteLine($"{d:r} : {l} : ({d == d2 ? "Equal" : "Different"})");

结果:

  6.0000000000004E+17 : 600000000000039936 : Equal

您可以尝试 decimal 而不是 double(特别是如果您正在处理财务数据):

  decimal d = 600000000000040000m; // m suffix

  long l = (long)d;

  decimal d2 = l;

  Console.WriteLine($"{d} : {l} : ({d == d2 ? "Equal" : "Different"})");

结果:

  600000000000040000 : 600000000000040000 : Equal

希望对您有所帮助。

// Double to long
           double av = 600000000000040000L;
            long lg = (long)av;
            long g1 = Convert.ToInt64(av);
// long to Double
            double dbl = (double)g1;
            double d = Convert.ToDouble(g1);