生成 9 位随机数,包括前导零 [英] Generation 9 digits random number including leading zero
问题描述
我想生成随机数,如果数字小于 9 位,它是 9 位包括前导零,比如 123 将是 000000123.我有以下代码不包括前导零:
I want to generate random number, which is 9 digits including leading zero if the number is less than 9 digits, say 123 will be 000000123. I have the following code which doesn't include leading zero :
Dim RandomClass As New Random()
Dim RandomNumber = RandomClass.Next(1, 999999999)
谢谢.
推荐答案
虽然我仍然很喜欢下面的单个数字"方法,但有一个更简单的方法 - 只需给出自定义数字格式:
While I still quite like my "individual digits" approach below, there's an easier way - just give a custom number format:
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 的格式字符串也可以完成这项工作:
As has been pointed out in the comments, a format string of D9 will also do the job:
Dim digits As String = number.ToString("D9")
就我个人而言,我必须确切地查找它会做什么,而我对自定义数字格式感到满意 - 但这更多地说明了我而不是代码:)
Personally I'd have to look up exactly what that would do, whereas I'm comfortable with custom number formats - but that says more about me than about the code :)
我不会生成 1 到 999999999 之间的单个数字,而是生成 0 到 9 之间的 9 个数字.基本上,您生成的是 字符串 而不是数字(因为数字 000000000 和 0 是等价的,但你不想要第一个).
Rather than generating a single number between 1 and 999999999, I would just generate 9 numbers between 0 and 9. Basically you're generating a string rather than a number (as numerically 000000000 and 0 are equivalent, but you don't want the first).
因此在字符数组中生成 9 个字符 '0' 到 '9',然后从中创建一个字符串.
So generate 9 characters '0' to '9' in a Character array, and then create a string from that.
这是一些示例 C# 代码:
Here's some sample C# code:
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:
... and converting it to 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.您实际上希望最小值是多少?
One point to note: this code can generate "000000000" whereas your original code had a minimum value of 1. What do you actually want the minimum to be?
这篇关于生成 9 位随机数,包括前导零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!