简体   繁体   English

使用VS2012在C#上进行错误的浮点转换

[英]Bad float conversion on C# using VS2012

I am getting a very weird behavior here with C#: 我在这里用C#得到了一个非常奇怪的行为:

float num = 144771463f;
// num is 144771456.0

I have also tried 我也试过了

float num = Convert.ToSingle(144771463f);
// num is still 144771456.0

Why does it happen? 为什么会这样?

You're hitting inherent limtations in the System.Single type ( float is a name-alias of Single ). 你在System.Single类型中遇到了固有的限制( floatSingle的名称别名)。

According to MSDN ( http://msdn.microsoft.com/en-us/library/system.single.aspx ) the Single type has 22 bits dedicated to the mantissa (also known as the significand), these are the bits that store the actual 'numbers' in the value (the other 10 bits store the positive/negative sign and the exponent). 根据MSDN( http://msdn.microsoft.com/en-us/library/system.single.aspx ), Single类型有22位专用于尾数(也称为有效数字),这些是存储的位值中的实际“数字”(其他10位存储正/负符号和指数)。

22 bits means you have an effective range of 0 - 4,194,304 - whereas the number you're storing is 144,771,463 , which is 2 decimal digits beyond the (approximate) 7-digit decimal precision of Single . 22位意味着你有一个有效范围0 - 4,194,304 -而要存储的号码是144,771,463 ,这是2个以外的(近似)7位十进制精度十进制数字Single So it will only store 144,771,46X (the value of the X digit won't be stored, but its magnitude will be stored in the exponent area). 因此它只存储144,771,46XX数字的值不会被存储,但其大小将存储在指数区域中)。

You have a few options: 你有几个选择:

  1. Use System.Double which provides for 51 bits of mantissa 使用System.Double ,提供51位尾数
  2. Use System.Decimal which provides for 96 bits of numeric information, note that Decimal handles mathematical operations specially in a way that preserves more information at a cost of speed (I do not know the technical details, sorry). 使用提供96位数字信息的System.Decimal ,注意Decimal特别以一种以牺牲速度为代价保存更多信息的方式处理数学运算(我不知道技术细节,对不起)。

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

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