Thursday, March 5, 2009

Getting a random Decimal in C#

I was writing some automated test cases the other day and I needed a System.Decimal that was different to the current decimal I had. Any old decimal would do, as long as it was different to the one I currently had. I thought, why no just grab a random one? Admittedly, I could just increment or decrement the one I currently had, but it bothered me that there didn't seem to be a easy way to get a random decimal (that includes Googling for some code that would do it for me).

I had a go at extending System.Random until is felt I was fairly close and then posted the question and my initial attempt to Stack Overflow.

See: Stack Overflow: Generating a Random Decimal in C#

It turns out there are a few gotchas with this. Firstly, getting a random signed (+/-) int from the random class requires careful consideration. Secondly, what kind of distribution of decimals was I actually after. There are multiple possible representations for the same number with the decimal class, so some numbers may come up more that others.