An array of C#, PHP, and HTML programming articles, tutorials, and resources

Posts Tagged ‘ number ’

To generate a random number between 0 and X, use the below javascript:

var myRandomNumber = Math.floor(Math.random()*(X+1))

Therefore, if you want from 0 and 100, you simply need:

var myRandomNumber = Math.floor(Math.random()*101)

Now, a bit more complicated! If we want a number between the range of X and Y, follow the below formula:

var myRandomNumber = Math.floor(Math.random()*(Y-X))+X

And another real world example. Assume we want a random number from 79 and 473:

var myRandomNumber = Math.floor(Math.random()*394)+79

A provided function of C# in the Math class is the function Round. The round function has two inputs. The first input field is of type double and the number requiring rounding. The second input type is of type int and indicates the precision of the first input field. This round function allows you to provide a degree of precision to your numbers.

public static double Round(double value, int digits)

A few important facts:

  1. When double value is rounded, if it is less than 5, it is rounded down. If it is equal to or greater than 5, the value is rounded up.
  2. Valid int digits are integer between 0 to 14.
  3. An int digit value of 0 will output a whole number.

Provided below is an working example:

double example = 12.34567;
double output = Math.Round(example, 3);

The value output in the above example equal 12.346.