简体   繁体   English

如何在C#中生成一个总共8位数的随机数? (4个整数,4个小数部分)

[英]How to generate a random number with 8 digits total in C#? (4 integer, 4 fractional part)

Something like these: 像这样的东西:

1234.5678
2345.6789
3456.7890

But not: 但不是:

123.4567

Right now I do this: 现在我这样做:

double number = Math.Ceiling ( random.NextDouble ( ) * 10000000 ) * 0.001;

but that doesn't always give me 8 digits. 但这并不总是给我8位数。

Any clever tricks to do this? 有什么聪明的技巧吗?

Try random.Next(10000000, 99999999+1) / 10000.0d; 尝试random.Next(10000000, 99999999+1) / 10000.0d;

EDIT: added more 9s 编辑:增加了9s

EDIT2: fixed the 1 minus issue EDIT2:修正了1减去问题

EDIT3: added more 0s, how did my answer get upvoted so much? 编辑3:添加更多0,我的答案是如何得到如此多的投票?

Use one of these: 使用以下其中一个:

double number = Math.Ceiling(random.NextDouble() * 9000 * 10000 + 1000 * 10000) * 0.0001;
double number = Math.Ceiling(random.NextDouble() * 90000000 + 10000000) * 0.0001;
double number = random.Next(10000 * 10000 / 10, 10000 * 10000) / 10000d;
double number = random.Next(10000000, 100000000) / 10000d;

Something like this? 像这样的东西?

Random r = new Random();
var item = r.Next(10000000, 100000000) * 0.0001m;

Per spender's comment below... explanation as to why you I use decimal here: 每个消费者的评论如下...解释为什么我在这里使用小数:

  1. Jon Skeet publicly shamed many of us for choosing double at one of his talks at Codemash in Ohio. Jon Skeet在俄亥俄州Codemash的一次会谈中公开羞辱了我们许多人选择加倍。
  2. Doubles are used by hipsters, and 赶时髦的人使用双打,和
  3. Decimal will prevent precision issues that are introduced by the use of double. Decimal将防止使用double引入的精度问题。 Keep in mind that when you need lots of digits after the dot, you should use double. 请记住,当您需要点后的大量数字时,您应该使用double。 If you need less, but need them to maintain accuracy, use decimal. 如果您需要更少,但需要它们保持准确性,请使用小数。

生成8个单个随机数字,然后将它们连接在一起。

double number = random.Next(1000 * 1000, 1000 * 1000 * 10) / 1000.0
double rndNumber = new Random().NextDouble(); 
string testNumber = (rndNumber * 99999999).ToString("0000.0000"); 
Random rnd = new Random();
int num1 = rnd.Next(1000,9999);
int num2 = rnd.Next(1000,9999);
Console.WriteLine(num1.ToString()+"."+num2.ToString());
double number = Double.Parse(r.Next(10000000, 99999999).ToString().Insert(4,"."));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM