Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Faker.js random number between 2 values

This one is driving me a little mad, I'm sure it's simple but it doesn't seem to be documented anywhere.

Im using Faker.js and the following to generate my random number:

faker.random.number(); 

Works great, now if I want to do it between 2 numbers, how would I go about this?

I tried the following:

faker.random.number(10, 50); 

However, that just gives me numbers from 0 to 10. No idea what the 50 is doing.

Can anyone give me some directions to this please.

like image 449
K20GH Avatar asked Aug 14 '15 13:08

K20GH


People also ask

How do you generate a random number between two values in JavaScript?

In JavaScript, you can generate a random number with the Math. random() function.

How does faker generate random numbers?

You need to give an object to the function: faker. datatype. number({ 'min': 10, 'max': 50 });

How do you assign a random number in JavaScript?

Javascript creates pseudo-random numbers with the function Math. random() . This function takes no parameters and creates a random decimal number between 0 and 1.


1 Answers

You need to give an object to the function:

faker.datatype.number({     'min': 10,     'max': 50 }); 

So if you just pass a number, it will set it as the max value. The min value is 0 by default.

This is the implementation of the number function :

this.number = function (options) {      if (typeof options === "number") {       options = {         max: options       };     }      options = options || {};      if (typeof options.min === "undefined") {       options.min = 0;     }      if (typeof options.max === "undefined") {       options.max = 99999;     }     if (typeof options.precision === "undefined") {       options.precision = 1;     }      // Make the range inclusive of the max value     var max = options.max;     if (max >= 0) {       max += options.precision;     }      var randomNumber = options.precision * Math.floor(       mersenne.rand(max / options.precision, options.min / options.precision));      return randomNumber;    } 

Update

Latest versions changed location of the function from faker.random.number to faker.datatype.number, https://github.com/Marak/faker.js/issues/1156

like image 170
cre8 Avatar answered Sep 20 '22 09:09

cre8