Hriskesh Ashokan
Hriskesh Ashokan

Reputation: 781

How to generate a random 10 digit number in C#?

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;
}

Upvotes: 34

Views: 101047

Answers (15)

Arthur Edgarov
Arthur Edgarov

Reputation: 731

The easiest and fastest way to generate digit numbers in .NET 8 and newer:

/// <summary>
/// "All dgits" string used to generate random digit codes.
/// </summary>
private const string Digits = "0123456789";

public string GenerateRandomDigitCode(int length)
    => RandomNumberGenerator.GetString(Digits, length);

Upvotes: 2

Sean
Sean

Reputation: 91

new string(Enumerable.Range(1, 10).Select(i => $"{System.Security.Cryptography.RandomNumberGenerator.GetInt32(0, 10)}"[0]).ToArray())

Upvotes: 0

wishmaster
wishmaster

Reputation: 1591

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.

Upvotes: 1

Menelaos Vergis
Menelaos Vergis

Reputation: 3955

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)

Upvotes: 7

Ravi Ganesan
Ravi Ganesan

Reputation: 295

// 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); 
    }
}

Upvotes: 3

A Ghazal
A Ghazal

Reputation: 2823

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;
}

Upvotes: 28

HamedH
HamedH

Reputation: 3273

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);
}

Upvotes: 1

Chtioui Malek
Chtioui Malek

Reputation: 11515

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.

Upvotes: 4

Oleg
Oleg

Reputation: 360

Random random = new Random();
string randomNumber = string.Join(string.Empty, Enumerable.Range(0, 10).Select(number => random.Next(0, 9).ToString()));

Upvotes: 0

DrWeather
DrWeather

Reputation: 96

private void button1_Click(object sender, EventArgs e)
{
   Random rand = new Random();
   long randnum2 = (long)(rand.NextDouble() * 9000000000) + 1000000000;
   MessageBox.Show(randnum2.ToString());
}

Upvotes: 4

mohghaderi
mohghaderi

Reputation: 2650

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;
}

Upvotes: 1

AVIK GHOSH
AVIK GHOSH

Reputation: 117

To generate a random 10 digit number in C#

Random RndNum = new Random();   

int RnNum = RndNum.Next(1000000000,9999999999);

Upvotes: -3

Yahia
Yahia

Reputation: 70369

try (though not absolutely exact)

Random R = new Random();

return ((long)R.Next (0, 100000 ) * (long)R.Next (0, 100000 )).ToString ().PadLeft (10, '0');

Upvotes: 12

Ray Toal
Ray Toal

Reputation: 88378

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'.

Upvotes: 5

Unsliced
Unsliced

Reputation: 10552

(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.

Upvotes: 3

Related Questions