0

Error:

$exception {"Value was either too large or too small for an Int32."} System.OverflowException

My code :

Random R = new Random();
if (NUD_1.Value > NUD_2.Value)
    return;
int v = R.Next((int)NUD_1.Value ,(int)NUD_2.Value);
    Label_generate2.Text = v.ToString();

I want generate number . but when i put a big number it givesme this error . NUD are the Numeric up downs .

Rand Random
  • 7,300
  • 10
  • 40
  • 88
  • The error message is pretty clear. `Random(int, int)` [only works with 32bit integers](https://msdn.microsoft.com/en-us/library/2dx6wyd4(v=vs.110).aspx). You pass 2 `Int32` 's and it returns an `Int32` – maccettura Jun 20 '18 at 16:38
  • So there isnt any way? How can i get bigger number than is the biggest int32 number . i want like 15 characters. –  Jun 20 '18 at 16:44

2 Answers2

1

All what you have to do is to declare:

Int64 NUD_1Value = NUD_1.Value;
Int64 NUD_2Value = NUD_2.Value;

Then use NUD_1Value instead of NUD.1Value

It will work


EDIT:

Check the below. It worked for me:

    Random R = new Random();

    double NUD_1Value = 1;
    double NUD_2Value = 999999999999999; //15-digit number

    var next = R.NextDouble();

    double v = NUD_1Value + (next * (NUD_2Value - NUD_1Value));

    MessageBox.Show(v.ToString());
Joe
  • 879
  • 3
  • 14
  • 37
  • works max with 14 digits . when i do 15 digits this error comes . + $exception {"'minValue' cannot be greater than maxValue.\r\nParameter name: minValue"} System.ArgumentOutOfRangeException –  Jun 20 '18 at 17:04
  • After Edit : Nice this Works . Thank you :) –  Jun 20 '18 at 17:30
  • I wrote a Test Method and saw this returns Redundant values. Copy these lines and test yourself: [TestMethod] public void TestRand64() { Int64 rnum = 0; HashSet hs = new HashSet(); for (int i = 0; i < 100000; i++) { rnum = GetInt64RandomNumber(); Assert.AreNotEqual(0, rnum); Assert.AreEqual(15, rnum.ToString().Length); if (!hs.Contains(rnum)) { hs.Add(rnum); } else { Console.Write(rnum + " : " + hs.Count.ToString()); Assert.Fail(); } } } – QMaster Dec 04 '19 at 10:57
0

Try:

long v = (long)Math.Round(NUD_1.Value + R.NextDouble() * ((double)NUD_2.Value - (double)NUD_1.Value));
user3100235
  • 127
  • 3