Unique 4 digit random number in C#

前端 未结 11 1909
失恋的感觉
失恋的感觉 2021-01-01 13:19

I want to generate an unique 4 digit random number. This is the below code what I have tried:

Code for generating random number

//Ge         


        
相关标签:
11条回答
  • 2021-01-01 13:55

    Just one line code

    int num = new Random().Next(1000, 9999);
    
    0 讨论(0)
  • 2021-01-01 13:59
    Random generator = new Random();
    string number = generator.Next(1, 10000).ToString("D4");
    
    0 讨论(0)
  • 2021-01-01 13:59

    You can consider something like this.

    int length = 4;
    int number = 50;
    string asString = number.ToString("D" + length);
    

    The above code gives the result 0050.

    Similarly you can try converting to string and verify.

    0 讨论(0)
  • 2021-01-01 14:03

    241 is a four digit number, if you use leading zeros: 0241.

    Display the returned number with a format string like this:

    String.Format("{0:0000}", n);

    0 讨论(0)
  • 2021-01-01 14:07

    0 is the same as 0000.

    241 is the same as 0241.

    You could format the integer to a string with a leading zero.

    0 讨论(0)
提交回复
热议问题