Generate random 6 digit number

前端 未结 6 2277
南方客
南方客 2020-12-29 20:25

I\'ve been searching for a couple of hours and I just can\'t seem to find a answer to this question. I want to generate a random number with 6 digits. Some of you might tell

相关标签:
6条回答
  • 2020-12-29 20:35

    As stated in a comment, a "six digit number" is a string. Here's how you generate a number from 0-999999, then format it like "000482":

    Random r = new Random();
    int randNum = r.Next(1000000);
    string sixDigitNumber = randNum.ToString("D6");
    
    0 讨论(0)
  • 2020-12-29 20:40

    I agree with the comment above that 000 001 can't be an integer, but can be a string with:

    Random generator = new Random();
    int r = generator.Next(1, 1000000);
    string s = r.ToString().PadLeft(6, '0');
    
    0 讨论(0)
  • 2020-12-29 20:49
    string s = generator.Next(0, 1000000).ToString("D6");
    

    or

    string s = generator.Next(0, 1000000).ToString("000000");
    
    0 讨论(0)
  • 2020-12-29 20:52
    private static string _numbers = "0123456789";
    Random random = new Random();
    
    
    private void DoWork()
    {
       StringBuilder builder = new StringBuilder(6);
       string numberAsString = "";
       int numberAsNumber = 0;
    
       for (var i = 0; i < 6; i++)
       {
          builder.Append(_numbers[random.Next(0, _numbers.Length)]);
       }
    
       numberAsString = builder.ToString();
       numberAsNumber = int.Parse(numberAsString);
    
    }
    
    0 讨论(0)
  • 2020-12-29 20:54

    You want to have a string:

    Random r = new Random();
    var x = r.Next(0, 1000000);
    string s = x.ToString("000000");
    

    For example,

    x = "2124"
    s = "002124"
    
    0 讨论(0)
  • 2020-12-29 20:56

    If you want a string to lead with zeroes, try this. You cannot get an int like 001.

        Random generator = new Random();
        String r = generator.Next(0, 1000000).ToString("D6");
    
    0 讨论(0)
提交回复
热议问题