Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net

random

math

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?

like image 417
Joan Venge Avatar asked Apr 19 '12 19:04

Joan Venge


1 Answers

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?

like image 173
Matthew Avatar answered Nov 07 '22 19:11

Matthew