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

后端 未结 13 1815
清歌不尽
清歌不尽 2020-12-15 18:00

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 r

相关标签:
13条回答
  • 2020-12-15 18:39

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

    0 讨论(0)
  • 2020-12-15 18:40
    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;
    }
    
    0 讨论(0)
  • 2020-12-15 18:41

    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.

    0 讨论(0)
  • 2020-12-15 18:43

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

    0 讨论(0)
  • 2020-12-15 18:44

    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)

    0 讨论(0)
  • 2020-12-15 18:45
    // 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); 
        }
    }
    
    0 讨论(0)
提交回复
热议问题