Why does 1 billion * 100 == 1.2 billion?

c#, math

Solution

Because multiple overflows are happening. Every time 2,147,483,647 is reached, the count starts over. Now, you have to keep in mind that it overflows to -2,147,483,648. So we have to take into account the whole Int32 range, which is 4,294,967,296 (it can be calculated from `(Int64)Int32.MaxValue + 1 - Int32.MinValue` or simply `2^32`.

The math:

(1 billion * 100) % (4,294,967,296) = 1215752192

Proof of concept in C# code:

var range = (Int64)Int32.MaxValue + 1 - Int32.MinValue;
Int64 val = 100000000000 % range;
Console.WriteLine(range);
Console.WriteLine(val);

Problem

I have code that sets a default value of a cell to the value of the cell above multiplied by 100: ``` const int DUCKBILL_MULTIPLIER = 100; . . . cellValue = dataGridViewPlatypi.Rows[args.RowIndex - 1].Cells[0].Value; if (Convert.ToInt32(cellValue) > 0) { int nextDefaultVal = Convert.ToInt32(cellValue) * DUCKBILL_MULTIPLIER; cellValue = nextDefaultVal; } prevVal = cellValue == null ? string.Empty : cellValue.ToString(); . . . dataGridViewPlatypi.Rows[args.RowIndex].Cells[args.ColumnIndex].Value = prevVal; ``` But once the value above gets to be 1000000000 (1 billion), the next value is 1215752192 (1,215,752,192 or approximately 1.2 billion) instead of 100 billion. I understand that the max int value is 2,147,483,647 (approximately 2.1 billion); so why is the next value 1,215,752,192 instead of 2,147,483,647? BTW, these vals are larger than the app will ever need to be, but I found this in testing "extreme" cases.

Original source