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

后端 未结 13 1769
清歌不尽
清歌不尽 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: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)

提交回复
热议问题