简体   繁体   English

如何从double转换为Int64

[英]How to Convert from double to Int64

I am trying to convert a double to an Int64 and get some strange behaviors. 我试图将双重转换为Int64并获得一些奇怪的行为。 To test my problem I tried the following code: 为了测试我的问题,我尝试了以下代码:

double temporary = Int64.MaxValue;
Int64 tem = Convert.ToInt64(temporary);

I still get an Overflow exception when converting the double to an Int64. 将double转换为Int64时,我仍然会遇到溢出异常。 Is this a bug? 这是一个错误吗? Or is there something I am not understanding? 或者有什么我不理解的东西?

The crux of this is that not all real numbers can be represented by finite floating point data types. 其关键在于并非所有实数都可以用有限浮点数据类型表示。 In particular, there are 64 bit integer values which do not have exact representation as double precision floating point values. 特别是,有64位整数值没有精确表示为双精度浮点值。

The value of Int64.MaxValue is 9,223,372,036,854,775,807 . Int64.MaxValue的值是9,223,372,036,854,775,807 The closest double precision value to this is 9,223,372,036,854,775,808 . 最接近的双精度值是9,223,372,036,854,775,808 So when 所以当

double temporary = Int64.MaxValue;

is executed, the value assigned to temporary is actually 9,223,372,036,854,775,808.0 . 执行时,分配给temporary的值实际为9,223,372,036,854,775,808.0

When you attempt to convert this double precision value to Int64 , an overflow occurs because the value exceeds Int64.MaxValue . 当您尝试将此双精度值转换为Int64 ,会发生溢出,因为该值超过Int64.MaxValue

A double cannot exactly represent Int64.MaxValue , so it gets rounded up. double不能完全代表Int64.MaxValue ,因此它会被四舍五入。 Since a long can't represent the rounded-up value, you get the exception. 由于long不能表示舍入值,因此您将获得异常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM