I want to generate random number, which is 9 digits including leading zero if the number is less than 9 digits, say 123 will be 000000123. I have the following code which doesn’t include leading zero :
Dim RandomClass As New Random()
Dim RandomNumber = RandomClass.Next(1, 999999999)
Thanks.
EDIT: While I still quite like my “individual digits” approach below, there’s an easier way – just give a custom number format:
C#:
VB:
EDIT: As has been pointed out in the comments, a format string of D9 will also do the job:
Personally I’d have to look up exactly what that would do, whereas I’m comfortable with custom number formats – but that says more about me than about the code 🙂
Rather than generating a single number between 1 and 999999999, I would just generate 9 numbers between 0 and 9. Basically you’re generating a string rather than a number (as numerically 000000000 and 0 are equivalent, but you don’t want the first).
So generate 9 characters ‘0’ to ‘9’ in a Character array, and then create a string from that.
Here’s some sample C# code:
… and converting it to VB:
One point to note: this code can generate “000000000” whereas your original code had a minimum value of 1. What do you actually want the minimum to be?