为什么 C# System.Decimal 会记住尾随零?
C# System.Decimal 是否会记住输入的尾随零的数量? 请参阅以下示例:
public void DoSomething()
{
decimal dec1 = 0.5M;
decimal dec2 = 0.50M;
Console.WriteLine(dec1); //Output: 0.5
Console.WriteLine(dec2); //Output: 0.50
Console.WriteLine(dec1 == dec2); //Output: True
}
小数被归类为相等,但 dec2 会记住它是通过附加零输入的。这样做的原因/目的是什么?
Is there a reason that a C# System.Decimal remembers the number of trailing zeros it was entered with?
See the following example:
public void DoSomething()
{
decimal dec1 = 0.5M;
decimal dec2 = 0.50M;
Console.WriteLine(dec1); //Output: 0.5
Console.WriteLine(dec2); //Output: 0.50
Console.WriteLine(dec1 == dec2); //Output: True
}
The decimals are classed as equal, yet dec2 remembers that it was entered with an additional zero. What is the reason/purpose for this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
小数表示固定精度的十进制值。文字值
0.50M
嵌入了 2 位小数精度,因此创建的小数变量会记住它是 2 位小数值。行为完全是设计使然。值的比较是对值的精确数值相等检查,因此此处尾随零不会影响结果。
Decimals represent fixed-precision decimal values. The literal value
0.50M
has the 2 decimal place precision embedded, and so the decimal variable created remembers that it is a 2 decimal place value. Behaviour is entirely by design.The comparison of the values is an exact numerical equality check on the values, so here, trailing zeroes do not affect the outcome.
它可以用来表示数字包括其精度 - 因此 0.5m 可用于表示“0.45m 到 0.55m 之间的任何值”(有适当的限制),而 0.50m 可用于表示“ 0.495m 和 0.545m 之间的任何值”。
我怀疑大多数开发人员实际上并没有使用此功能,但我可以看到它有时会有用。
我相信这种能力首先出现在 .NET 1.1 中,顺便说一句 - 我认为 1.0 中的小数总是被有效地标准化。
It can be useful to represent a number including its accuracy - so 0.5m could be used to mean "anything between 0.45m and 0.55m" (with appropriate limits) and 0.50m could be used to mean "anything between 0.495m and 0.545m".
I suspect that most developers don't actually use this functionality, but I can see how it could be useful sometimes.
I believe this ability first arrived in .NET 1.1, btw - I think decimals in 1.0 were always effectively normalized.
我认为这样做是为了为从数据库检索的数值提供更好的内部表示。数据库引擎在以十进制格式存储数字(避免舍入错误)方面有着悠久的历史,并明确指定了值中的位数。
例如,比较 SQL Server 十进制和数字列类型。
I think it was done to provide a better internal representation for numeric values retrieved from databases. Dbase engines have a long history of storing numbers in a decimal format (avoiding rounding errors) with an explicit specification for the number of digits in the value.
Compare the SQL Server decimal and numeric column types for example.