Why is the result of Decimal.MaxValue 0.5 integer?

Today I played with decimal. I noticed this:

Decimal.MaxValue 
79228162514264337593543950335

Decimal.MaxValue - 0.5m
79228162514264337593543950334

The following code prints true.

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, but I do not know what it is.

+5
source share
3 answers

The decimal type uses 96 bits to store a sequence of digits ( ref ) plus a sign (1 bit) and a scaling factor that determines the location of the decimal point.

For this decimal:

79228162514264337593543950335

All 96 bits are used to the left of the decimal point - nothing is left to represent the fractional part of the answer. Thus, it is rounded.

If you divide the number by 10:

7922816251426433759354395033.5

, , 1/10, .

decimal double/float , , ; , .

+11

0.5 . decimal , 79228162514264337593543950335 - 00000000000000000000000000000.5. 0.5 decimal 1.

+1

, Decimal.

(Int32) 2,147,483,648 2,147,483,647.

As you can see, this is good from these ranges.

In terms of display and accuracy 79228162514264337593543950334.5it cannot be represented Decimal.

Read this for more details (What Every Computer Scientist Should Know About Floating-Point Arithmetic).

0
source

All Articles