1

As the title says ... is it possible to create a random 16 digit number with jquery?

Satch3000
  • 47,356
  • 86
  • 216
  • 346
  • 5
    `Math.round(Math.random()*1E16)` – Chad Feb 02 '12 at 22:24
  • 1
    http://stackoverflow.com/questions/1527803/generating-random-numbers-in-javascript – mrtsherman Feb 02 '12 at 22:24
  • jquery doesn't have any utilities to accomplish this, you'll have to just use plain javascript. – driangle Feb 02 '12 at 22:25
  • Hello @Stach3000, I just need to tell you that the current accepted answer is not error-free, and even when taking some extreme measures it could still fail http://jsfiddle.net/KF5tD/ (refresh few times) – ajax333221 Feb 03 '12 at 19:07

8 Answers8

14

Just use:

Math.floor(Math.random()*1E16)

EDIT :

Note that there is about a 1/10 chance of a lower number of digits. If Math.random() generates something like 0.0942104924071337 then 0.0942104924071337 * 1E16 is 0942104924071337 which evaluates to 942104924071337; a 15 digit number.

The only way to 100% guarantee that the number is 16 digits in length is to have it be formed as a string. Using this method I would recommend @rjmunro's answer:

number = (Math.random()+' ').substring(2,10)+(Math.random()+' ').substring(2,10);
Chad
  • 19,219
  • 4
  • 50
  • 73
  • please, someone explain me the `1E16` :) – ajax333221 Feb 03 '12 at 01:10
  • Its the abbreviated form of scientific notation. so `1E16 == 1*(10^16)`. You can see more info [here](http://en.wikipedia.org/wiki/Scientific_notation#E_notation) – Chad Feb 03 '12 at 01:20
  • I believe you didn't meant to use `Math.floor` since that would generate numbers from `0-15` – ajax333221 Feb 03 '12 at 01:40
  • @ajax333221 The `Math.floor()` is just there to truncate the decimal place that is left after creating a 16 digit mantissa with `Math.random()*1E16`. This will *not* generate a number from `0 - 15` – Chad Feb 03 '12 at 15:39
  • I see, My mistake was to replace the `1E16` for `16` (which obviously isn't correct). Sorry for wasting your time. – ajax333221 Feb 03 '12 at 18:05
  • I would just have removed my upvote, but It was locked. I just think that answers that don't work properly shouldn't deserve to be upvoted by me. If somehow I see the way to remove it, I will. Don't take it personally. – ajax333221 Feb 04 '12 at 00:36
8

Not with jQuery, no, but you can do it with plain javascript.

If you want exactly 16 digits (possibly including leading 0s), I would start with Math.random(), convert to a string, pick 8 digits, and concatenate 2 runs together.

number = (Math.random() + '').substring(2,10)
  + (Math.random() + '').substring(2,10);
rjmunro
  • 27,203
  • 20
  • 110
  • 132
5

No, use JAVASCRIPT!

jQuery is not some magic genie.

Diodeus - James MacFarlane
  • 112,730
  • 33
  • 157
  • 176
1

I just tried with @rjmunro 's answer.
Unfortunately, it does generate string less than 16digits,
but very rare, approxly once in 10 million times.

Here is my testing code, runs in nodejs:

'use strict';
var fs = require('fs');
var totalTimes = 100000000;
var times = totalTimes;
var fileName;
var writeStream;

while (times > 0) {
  var key = (Math.random() + ' ').substring(2,10) + (Math.random() + ' ').substring(2,10);
  times --;
  if (key.length !== 16) {
    var msg = 'a flaw key gened: ' + key + '\n';
    // create a log file at first time
    if (!fileName) {
      fileName = 'log/flaw_key_' + new Date() + '.txt';
    }
    writeStream = fs.createWriteStream(fileName);
    writeStream.write(msg);
    writeStream.end();
  }
  if (times === 0) {
    console.log(totalTimes + ' times key gened');
  }
}

Also @Dimitri Mikadze 's answer generate less length string as well, so I eventually adopt a way with some concept of his solution:

function getRandomInt(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

/**
 * Gen random digits string in specific length
 * @param {Int} length of string
 *
 * @return {String}
 *
 */
function genString(length) {
  var times = length;
  var key = '';
  while (times > 0) {
    times --;
    key += getRandomInt(0, 9);
  }
  return key;
}

genString(16); // a 16 digits string
ddhp
  • 88
  • 7
1

This is a task which is much better suited for raw javascript. For example

var str = '';
var i;
for (i = 0; i < 16; i++) {
  var number = Math.floor(Math.random() * 10) % 10;
  str += number;
}
JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454
  • It's not just "better suited to raw javascript", it has nothing to do with jQuery whatsoever. It's like saying "How can I make apple pie using only oranges?" – rjmunro Feb 03 '12 at 23:54
0

u can use this function to generate random digits, just pass minimum and maximum parameters

function randomInt(min, max) {

    return Math.floor(Math.random() * (max - min + 1) + min);
}

random 16 digit, usage

randomInt(0, 9999999999999999);
Dimi Mikadze
  • 474
  • 5
  • 10
0

I know this question is old but this simple function will guarantee a 16 (or however many you want) character string every time without the 10% failure rate of other solutions. Can change it to a number if you need to.

function generate() {
        let string = ""
    
        while (string.length < 16) {
            let number = Math.floor(Math.random() * 10).toString()
            string += number
        }
        return string
    }
cfech
  • 16
  • 2
0

I think this way is more beautiful:

const generateFixedLengthNumberInString = length =>
  [...Array(length).keys()].reduce(
    previousValue =>
      previousValue + String(Math.floor(Math.random() * 10) % 10),
  );
console.log(generateFixedLengthNumberInString(16))
// prints "0587139224228340"

Behrad Kazemi
  • 302
  • 1
  • 10