为什么Decimal.MaxValue-0.5的结果是整数? [英] Why is the result of Decimal.MaxValue - 0.5 an integer?
问题描述
我今天在玩小数。我注意到了这一点:
I was playing with decimal today. I noticed this:
Decimal.MaxValue
79228162514264337593543950335
Decimal.MaxValue - 0.5m
79228162514264337593543950334
以下代码显示为真。
static void Main(string[] args)
{
decimal d = Decimal.MaxValue - 0.5M;
var b = d % 1 == 0;
Console.WriteLine(b);
}
我确定这是有原因的,但我不知道
I am sure there is a reason behind this but I don't know what it is.
推荐答案
十进制类型使用96位存储数字序列( ref ),外加一个符号(1位)和一个比例系数,用于指定位置
The decimal type uses 96 bits to store the sequence of digits (ref), plus a sign (1 bit) and a scaling factor that specifies the location of the decimal place.
对于此十进制数字:
79228162514264337593543950335
所有96位都用在小数点的左侧-剩下的任何数字都不能表示小数部分的答案。因此,它将四舍五入。
All 96 bits are used to the left of the decimal point - there's nothing left to represent the fractional part of the answer. So, it gets rounded.
如果将数字除以10:
7922816251426433759354395033.5
然后,您可以使用一些位来表示小数部分,但只表示1 / 10,再好一点。
Then you have a few bits available to represent the fractional part - but only to 1/10, no finer.
十进制
和 double
/ float
是基于小数位缩放因子,指定了小数点的位置;其他浮动类型基于 binary 比例因子,该比例因子指定了 binary点的位置。
The key difference between decimal
and double
/float
is that it is based on a decimal scaling factor specifying the location of a decimal point; the other floating types are based on a binary scaling factor specifying the location of a binary point.
这篇关于为什么Decimal.MaxValue-0.5的结果是整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!