问题描述
我有以下代码来测试从 double 到 long 的转换:
I have the following code to test the conversion from double to long:
double dVal = (double)(long.MaxValue); // 9.2233720368547758E+18;
if (dVal <= long.MaxValue && dVal >= long.MinValue)
{
long lVal1 = (long)(dVal); // gives -9223372036854775808 !!!
Console.WriteLine($"lVal1 = {lVal1}");
long lVal2 = Convert.ToInt64(dVal); // gives System.OverflowException
}
我预计 lVal1/2 为 9223372036854775807 或 9223372036854775800,因为双精度型中存在截断或四舍五入.
I expected lVal1/2 to be 9223372036854775807 or 9223372036854775800 because of the truncation or rounding in the double type.
如何在所有情况下正确地将 double 转换为 long?框架中是否已经存在某些内容,或者我是否需要实施它?
How can I convert double to long correctly for all cases? Is there something in the framework already or do I need to implement it?
推荐答案
你为什么期望你所期望的?C# 文档非常清楚在这两种情况下会发生什么:
Why do you expect what you expect? The C# docs are pretty clear about what happens in these two cases:
案例 1:使用显式转换从 double 进行转换(来自 这里)
Case 1: Casting from double using an explicit cast (from here)
当您从 double 或 float 值转换为整型时,值被截断.如果所得的积分值在目标值的范围,结果取决于溢出检查上下文.在检查的上下文中,OverflowException 是抛出,而在未经检查的上下文中,结果是未指定的目标类型的值.
案例 2:调用 Convert.ToInt64(来自 这里)
Case 2: Calling Convert.ToInt64 (from here)
异常
溢出异常
值大于 MaxValue 或小于 MinValue.
value is greater than MaxValue or less than MinValue.
您的问题的答案取决于您希望它在这些情况下做什么?您必须进行显式转换的原因是因为有可能丢失信息(因为双打可以存储不适合 long 的值).你必须告诉编译器你想在这些边缘情况下做什么.
The answer to your question depends on what you want it to do in these cases? The reason you have to do an explicit cast is because there is a possibility to lose information (since doubles can store values that don't fit into a long). You have to tell the compiler what you want to do in these edge cases.
这篇关于C#:双到长转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!