dotnetandsqldevelop dotnetandsqldevelop - 2 months ago 19
C# Question

Random double between given numbers

I'm looking for some succinct, modern C# code to generate a random double number between

1.41421
and
3.14159
. where the number should be
[0-9]{1}.[0-9]{5}
format.

I'm thinking some solution that utilizes
Enumerable.Range
somehow may make this more succinct.

Answer

You can easily define a method that returns a random number between two values:

private static readonly Random random = new Random();

private static double RandomNumberBetween(double minValue, double maxValue)
{
    var next = random.NextDouble();

    return minValue + (next * (maxValue - minValue));
}

You can then call this method with your desired values:

RandomNumberBetween(1.41421, 3.14159)
Comments