13,351,050 members (54,230 online)
alternative version

#### Stats

16.9K views
8 bookmarked
Posted 30 Jun 2008

# generate random numbers

, 30 Jun 2008
 Rate this:
Easy way to generate random real (float) or integer numbers

## Introduction

The main idea for this article is how to create random floating numbers in .NET. Before few days i faced problem for generating random real numbers for Stock markets and i searched for a code in CodeProject but i didn't found useful way for this problem.

## RandomFloat Class

The RandomFloat class contains properties that allow user to generate random real-integer numbers between specific range and flag to turn on/off real number generator.

## Using the code

Turn on or off the real number generator by set the AllowFloating property to true or false, then call the override method NextDouble()

```public class RandomFloat : Random
{
protected const int DEFAULT_MIN_VAL = 1;
protected const int DEFAULT_MAX_VAL = 10;

protected bool m_bAllowFloat;
protected int m_iMinVal = DEFAULT_MIN_VAL;
protected int m_iMaxVal = DEFAULT_MAX_VAL;

public RandomFloat()
{
}

public RandomFloat(bool bAllowFloat)
{
m_bAllowFloat = bAllowFloat;
}

public bool AllowFloating
{
get
{
return m_bAllowFloat;
}
set
{
m_bAllowFloat = value;
}
}

public int MinRange
{
get
{
return m_iMinVal;
}
set
{
m_iMinVal = value;
}
}

public int MaxRange
{
get
{
return m_iMaxVal;
}
set
{
m_iMaxVal = value;
}
}

public override double NextDouble()
{
int iRnd = Next(m_iMinVal, m_iMaxVal);
double fRnd = base.NextDouble();

if (m_bAllowFloat)
{
if (iRnd < 0)
fRnd = iRnd + (fRnd * -1);
else
fRnd += iRnd;
}
else
fRnd = iRnd;

if (fRnd > m_iMaxVal)
fRnd = m_iMaxVal;

return fRnd;
}
}
```

## Share

 Software Developer (Senior) Optimiza Jordan
No Biography provided

## You may also be interested in...

 First Prev Next
 Generate random numbers AnithaJoseph8529-Apr-09 2:38 AnithaJoseph85 29-Apr-09 2:38
 Computers can't create true random numbers seesharper30-Jun-08 22:35 seesharper 30-Jun-08 22:35
 Last Visit: 31-Dec-99 19:00     Last Update: 19-Jan-18 15:51 Refresh 1