第9代数字随机数,包括前导零

时间:2010-07-15 06:58:04

标签: vb.net

我想生成随机数,如果数字小于9位,则为9位数,包括前导零,假设123为000000123。我有以下代码,不包括前导零:

Dim RandomClass As New Random()
Dim RandomNumber = RandomClass.Next(1, 999999999)

感谢。

3 个答案:

答案 0 :(得分:7)

编辑:虽然我仍然非常喜欢下面的“个别数字”方法,但有一种更简单的方法 - 只需提供自定义数字格式:

C#:

Random rng = new Random();
int number = rng.Next(1, 1000000000);
string digits = number.ToString("000000000");
Console.WriteLine(digits);

VB:

Dim rng As New Random
Dim number As Integer = rng.Next(1, 1000000000)
Dim digits As String = number.ToString("000000000") 
Console.WriteLine(digits)

编辑:正如评论中指出的那样,D9的格式字符串也可以完成这项工作:

Dim digits As String = number.ToString("D9") 

就我个人而言,我必须准确查看它会做什么,而我对自定义数字格式感到满意 - 但这更多地说明了我而不是代码:)


我不会在1到999999999之间生成一个数字,而是在0到9之间生成9个数字。基本上你生成一个字符串而不是一个数字(数字为000000000和0)等价,但你不想要第一个。)

因此在Character数组中生成9个字符'0'到'9',然后从中创建一个字符串。

以下是一些C#代码示例:

using System;

class Test
{
    static void Main(string[] args)
    {
        Random rng = new Random();
        string digits = GenerateDigits(rng, 9);
        Console.WriteLine(digits);
    }

    static string GenerateDigits(Random rng, int length)
    {
        char[] chars = new char[length];
        for (int i = 0; i < length; i++)
        {
            chars[i] = (char)(rng.Next(10) + '0');            
        }
        return new string(chars);
    }
}

...并将其转换为VB:

Public Class Test

    Public Shared Sub Main()
        Dim rng As New Random
        Dim digits As String = Test.GenerateDigits(rng, 9)
        Console.WriteLine(digits)
    End Sub

    Private Shared Function GenerateDigits(ByVal rng As Random, _
                     ByVal length As Integer) As String
        Dim chArray As Char() = New Char(length  - 1) {}
        Dim i As Integer
        For i = 0 To length - 1
            chArray(i) = Convert.ToChar(rng.Next(10) + &H30)
        Next i
        Return New String(chArray)
    End Function

End Class

需要注意的一点是:此代码可以生成“000000000”,而原始代码的最小值为1.您实际上希望最小值是什么?

答案 1 :(得分:3)

您需要将变量声明为类型字符串。整数不能有前导零。检查下面的示例:

 Dim RandomClass As New Random()


    Dim randomString As String


    For i = 1 To 1000 Step 1

        randomString = RandomClass.Next(1, 999999999).ToString

        If randomString.Length < 9 Then
            randomString = randomString.PadLeft(9, "0")
        End If
        Response.Write(randomString & "<br/>")
    Next

答案 2 :(得分:2)

999999999是合法价值吗?如果是的话......

'
Dim myRand As New Random
'
Private Function NineDigitRand() As String
    'return a numeric string between 000000001 and 999999999 inclusive
    Return myRand.Next(1, 1000000000).ToString("d9")
End Function