31

I'm using C# and I need to generate a random 10 digit number. So far, I've only had luck finding examples indicating min maximum value. How would i go about generating a random number that is 10 digits, which can begin with 0, (initially, I was hoping for random.Next(1000000000,9999999999) but I doubt this is what I want).

My code looks like this right now:

[WebMethod]
public string GenerateNumber()
{
    Random random = new Random();
    return random.Next(?);
}

**Update ended up doing like so,

[WebMethod]
public string GenerateNumber()
{
    Random random = new Random();
    string r = "";
    int i;
    for (i = 1; i < 11; i++)
    {
        r += random.Next(0, 9).ToString();
    }
    return r;
}
wonea
  • 4,783
  • 17
  • 86
  • 139
Hriskesh Ashokan
  • 741
  • 5
  • 16
  • 28
  • 2
    Would nine zeros followed by a 1 be valid for you? If so, couldnt you just make a random number and pad with zeros? – Paul Phillips Aug 14 '11 at 06:55
  • 1
    Thanks, I found this a helpful reference. I'd point out that reassigning the string with += works fine, but is inefficient. The StringBuilder class can save you a bit of memory here especially if someone applies this to a much larger string. – mikey Feb 08 '12 at 19:21
  • 1
    Random random = new Random(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < 10; i++) { sb.Append(random.Next(0, 9).ToString()); } return sb.ToString(); – mikey Feb 08 '12 at 19:22
  • 2
    1) What are you using this number for? Anything security related? The numbers you currently create are very predictable. 2) How uniform should the distribution be? With your current code only 20% of the numbers can be reached at all, and some will be much more likely than others. – CodesInChaos Apr 28 '12 at 22:28
  • +1 for update :) , `random.Next(1000000000,9999999999)` generate error!!! – AminM Jun 07 '13 at 04:57

14 Answers14

24

Use this to create random digits with any specified length

public string RandomDigits(int length)
{
    var random = new Random();
    string s = string.Empty;
    for (int i = 0; i < length; i++)
        s = String.Concat(s, random.Next(10).ToString());
    return s;
}
wonea
  • 4,783
  • 17
  • 86
  • 139
A Ghazal
  • 2,693
  • 1
  • 19
  • 12
  • 3
    Do not use this function if you intend on using it more than once. The random object should be declared outside the function scope as each time it will create a new instance of the Random object which can mean same number is generated. See http://stackoverflow.com/a/5264434/6099813 – Danhol86 Jan 17 '17 at 14:36
  • 1
    @Danhol86 This does not have the same issue as the link you posted. What you posted specifies a seed in the constructor while this does not. If you do not specify a seed, a seed will be generated from the system clock which mostly guarantees different numbers. Still good to know about either way. – Caboosetp Nov 15 '17 at 18:19
12

try (though not absolutely exact)

Random R = new Random();

return ((long)R.Next (0, 100000 ) * (long)R.Next (0, 100000 )).ToString ().PadLeft (10, '0');
Yahia
  • 69,653
  • 9
  • 115
  • 144
  • What's the purpose of multiplying two numbers together instead of just doing a single multiplication? – Captain Prinny Jan 27 '20 at 20:41
  • It will not cover all 10 digit numbers. This method will not cover prime number in 10 digit number range. – VSB Mar 05 '20 at 13:18
5

To get the any digit number without any loop, use Random.Next with the appropriate limits [100...00, 9999...99].

private static readonly Random _rdm = new Random();
private string PinGenerator(int digits)
{
   if (digits <= 1) return "";

   var _min = (int)Math.Pow(10, digits - 1);
   var _max = (int)Math.Pow(10, digits) - 1;
   return _rdm.Next(_min, _max).ToString();
}

This function calculated the lower and the upper bounds of the nth digits number.

To generate the 10 digit number use it like this:

PinGenerator(10)

Menelaos Vergis
  • 3,715
  • 5
  • 30
  • 46
5

If you want ten digits but you allow beginning with a 0 then it sounds like you want to generate a string, not a long integer.

Generate a 10-character string in which each character is randomly selected from '0'..'9'.

Ray Toal
  • 86,166
  • 18
  • 182
  • 232
4
private void button1_Click(object sender, EventArgs e)
{
   Random rand = new Random();
   long randnum2 = (long)(rand.NextDouble() * 9000000000) + 1000000000;
   MessageBox.Show(randnum2.ToString());
}
Opal
  • 81,889
  • 28
  • 189
  • 210
DrWeather
  • 76
  • 7
4
// ten digits 
public string CreateRandomNumber
{
    get
    {
        //returns 10 digit random number (Ticks returns 16 digit unique number, substring it to 10)
        return DateTime.UtcNow.Ticks.ToString().Substring(8); 
    }
}
wonea
  • 4,783
  • 17
  • 86
  • 139
Ravi Ganesan
  • 277
  • 6
  • 11
  • 2
    How is this a random number? – Neil Masson Dec 29 '15 at 20:18
  • Whenever you call this function, it will return a different value. That's almost like random value.This solution works for me: I only need to get different values each time I call it, no matter what the value is. – EAmez Mar 24 '17 at 09:37
  • In certain circumstances, this code can produce duplicates. Do some research on it. I have had similar code that when used in a loop would work just fine, but move it to a faster computer and it return duplicates a few times in a row here or there. Quite annoying to track down. Also, a change in time or having multiple computers running the code. I'm just saying. – user1544428 May 27 '22 at 18:05
4

I came up with this method because I dont want to use the Random method :

public static string generate_Digits(int length)
{
    var rndDigits = new System.Text.StringBuilder().Insert(0, "0123456789", length).ToString().ToCharArray();
    return string.Join("", rndDigits.OrderBy(o => Guid.NewGuid()).Take(length));
}

hope this helps.

Chtioui Malek
  • 11,197
  • 1
  • 72
  • 69
3

(1000000000,9999999999) is not random - you're mandating that it cannot begin with a 1, so you've already cut your target base by 10%.

Random is a double, so if you want a integer, multiply it by 1,000,000,000, then drop the figures after the decimal place.

Unsliced
  • 10,404
  • 8
  • 51
  • 81
  • 1
    I'm not sure random has anything to do with range. You may be describing predictability rather than randomness? – Lucas May 31 '20 at 17:42
1
private static Random random = new Random((int)DateTime.Now.Ticks);//thanks to McAden

public long LongBetween(long maxValue, long minValue)
{
    return (long)Math.Round(random.NextDouble() * (maxValue - minValue - 1)) + minValue;
}
herohuyongtao
  • 49,413
  • 29
  • 133
  • 174
mohghaderi
  • 2,520
  • 1
  • 19
  • 12
1

I tried to write a fast one:

private int GetNDigitsRandomNumber(int digits)
{
    var min = 1;
    for (int i = 0; i < digits-1; i++)
    {
          min *= 10;
    }
    var max = min * 10;

    return _rnd.Next(min, max);
}
HamedH
  • 2,814
  • 1
  • 26
  • 37
  • This won't work for ten digits, as the range of values representable by `int` is ~±2*10^9 - so once `min` is 10^8 you'll overflow and get unexpected values for `max`. – Wai Ha Lee Jan 03 '20 at 09:30
0
Random random = new Random();
string randomNumber = string.Join(string.Empty, Enumerable.Range(0, 10).Select(number => random.Next(0, 9).ToString()));
Oleg
  • 350
  • 4
  • 6
0

Here is a simple solution using format string:

string r = $"{random.Next(100000):00000}{random.Next(100000):00000}";

Random 10 digit number (with possible leading zeros) is produced as union of two random 5 digit numbers. Format string "00000" means leading zeros will be appended if number is shorter than 5 digits (e.g. 1 will be formatted as "00001").

For more about the "0" custom format specifier please see the documentation.

wishmaster
  • 1,469
  • 3
  • 13
  • 20
0
new string(Enumerable.Range(1, 10).Select(i => $"{System.Security.Cryptography.RandomNumberGenerator.GetInt32(0, 10)}"[0]).ToArray())
Sean
  • 91
  • 4
-3

To generate a random 10 digit number in C#

Random RndNum = new Random();   

int RnNum = RndNum.Next(1000000000,9999999999);
Brian Webster
  • 30,033
  • 48
  • 152
  • 225
AVIK GHOSH
  • 107
  • 1
  • 3