Imagine a typical clicker-game where the user gets a score of several millions, billions, gazillions and a lot of made-up gigantic numbers. Of course, none of those will fit in standard float representation.
What is a nice approach to represent those numbers in code?
I’ve looked around and believe that the decimal data structure from .NET has the highest precision, but comparing that to what our game designer wants, is still not enough. As a programmer, I would simply store one of the bigger numbers as double or similar and then multiply the display value. However, our designer wants the number to be incredibly big, but still accurate down to a single digit. So basically, he wants to be able to add 1 to a gazillion.
My approach: Create a dynamic data structure, basically a list of digits. Each digit only goes from 0-9 and the list can be expanded in a way that lets me represent enough numbers to satisfy my designer. But then I would need to convert all my math to this rather complex system of dialing digits up and down when adding numbers together.
If you’re just adding and subtracting, and your numbers are positive, then doing math directly on strings is not too difficult; it’s basically the addition and subtraction algorithms we are taught in elementary school. (Well, until Common Core, at least; not sure if this is still the case.) You’ll probably want to pad the strings with leading zeroes before adding until they’re the same length (and probably a single zero beyond their current size, so that a carried 1 won’t mess things up), so that the index lines up. Once that is done, you can just go digit by digit, and carry or borrow from the neighboring digits as needed. Use int.Parse(numberString[index]) to get the 0-9 value of a given digit. If adding, check to see if >= 10, and if so, you recursively add 1 to the digit to the left; if subtracting, you recursively subtract 1 from the digit to the left. And you’ll probably want to start on the right (highest index) and work your way over.
Using a string directly to store your big number will also make it easy for your designer to just type in whatever numbers he wants.
If you want to roll your own though… I’d use an array of some integer type… bytes, uints, something like that. Where each slot holds from 0->maxvalue for the type. And do the arithmetic that way. That way you’re not doing digit per digit addition.