在.NET中,十进制、浮点和双精度之间有什么区别?
什么时候有人会用这些?
在.NET中,十进制、浮点和双精度之间有什么区别?
什么时候有人会用这些?
当前回答
没有人提到
在默认设置中,Floats(System.Single)和doubles(System.Double)永远不会使用Decimal(System.Decimal)将始终使用溢出检查。
我是说
decimal myNumber = decimal.MaxValue;
myNumber += 1;
引发OverflowException。
但这些并不:
float myNumber = float.MaxValue;
myNumber += 1;
&
double myNumber = double.MaxValue;
myNumber += 1;
其他回答
浮点7位精度
双精度约为15位
十进制大约有28位精度
如果您需要更好的精度,请使用double而不是float。在现代CPU中,两种数据类型的性能几乎相同。使用浮子的唯一好处是它们占用更少的空间。只有当你有很多人的时候,才有实际意义。
我觉得这很有趣。每个计算机科学家都应该知道浮点运算
这对我来说是一个有趣的线索,因为今天,我们刚刚遇到了一个令人讨厌的小错误,关于十进制比浮点精度低。
在我们的C#代码中,我们从Excel电子表格中读取数字值,将其转换为十进制,然后将该十进制发送回服务以保存到SQL Server数据库中。
Microsoft.Office.Interop.Excel.Range cell = …
object cellValue = cell.Value2;
if (cellValue != null)
{
decimal value = 0;
Decimal.TryParse(cellValue.ToString(), out value);
}
现在,对于我们几乎所有的Excel值,这都非常有效。但是对于一些非常小的Excel值,使用decimal.TryParse完全丢失了值。一个这样的例子是
单元格值=0.00006317592Decimal.TryParse(cellValue.ToString(),out值);//将返回0
奇怪的是,解决方案是先将Excel值转换为双精度值,然后再转换为十进制值:
Microsoft.Office.Interop.Excel.Range cell = …
object cellValue = cell.Value2;
if (cellValue != null)
{
double valueDouble = 0;
double.TryParse(cellValue.ToString(), out valueDouble);
decimal value = (decimal) valueDouble;
…
}
即使double的精度低于十进制,这实际上确保了小数字仍然可以被识别。由于某种原因,double.TryParse实际上能够检索这样的小数字,而decimal.TryPars将它们设置为零。
古怪的非常奇怪。
对于游戏和嵌入式系统等内存和性能都至关重要的应用程序,浮点运算通常是数字类型的选择,因为它速度更快,大小只有双倍运算的一半。整数曾经是首选的武器,但在现代处理器中,浮点性能已经超过了整数。十进制是正确的!
浮动:±1.5 x 10^-45至±3.4 x 10^38(~7个有效数字双倍:±5.0 x 10^-324至±1.7 x 10^308(15-16个有效数字)小数:±1.0 x 10^-28至±7.9 x 10^28(28-29个有效数字)
+---------+----------------+---------+----------+---------------------------------------------------------+
| C# | .Net Framework | Signed? | Bytes | Possible Values |
| Type | (System) type | | Occupied | |
+---------+----------------+---------+----------+---------------------------------------------------------+
| sbyte | System.Sbyte | Yes | 1 | -128 to 127 |
| short | System.Int16 | Yes | 2 | -32,768 to 32,767 |
| int | System.Int32 | Yes | 4 | -2,147,483,648 to 2,147,483,647 |
| long | System.Int64 | Yes | 8 | -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 |
| byte | System.Byte | No | 1 | 0 to 255 |
| ushort | System.Uint16 | No | 2 | 0 to 65,535 |
| uint | System.UInt32 | No | 4 | 0 to 4,294,967,295 |
| ulong | System.Uint64 | No | 8 | 0 to 18,446,744,073,709,551,615 |
| float | System.Single | Yes | 4 | Approximately ±1.5e-45 to ±3.4e38 |
| | | | | with ~6-9 significant figures |
| double | System.Double | Yes | 8 | Approximately ±5.0e-324 to ±1.7e308 |
| | | | | with ~15-17 significant figures |
| decimal | System.Decimal | Yes | 16 | Approximately ±1.0e-28 to ±7.9e28 |
| | | | | with 28-29 significant figures |
| char | System.Char | N/A | 2 | Any Unicode character (16 bit) |
| bool | System.Boolean | N/A | 1 / 2 | true or false |
+---------+----------------+---------+----------+---------------------------------------------------------+
请参阅此处了解更多信息。