简体   繁体   中英

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.

Any clever tricks to do this?

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

EDIT: added more 9s

EDIT2: fixed the 1 minus issue

EDIT3: added more 0s, how did my answer get upvoted so much?

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.
  2. Doubles are used by hipsters, and
  3. Decimal will prevent precision issues that are introduced by the use of double. Keep in mind that when you need lots of digits after the dot, you should use 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,"."));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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