How to Generate a random number of fixed length using JavaScript?

杀马特。学长 韩版系。学妹 提交于 2019-12-02 17:51:27
Cilan

console.log(

    Math.floor(100000 + Math.random() * 900000)

);

Will always create a number of 6 digits and it ensures the first digit will never be 0. The code in your question will create a number of less than 6 digits.

Only fully reliable answer that offers full randomness, without loss. The other ones prior to this answer all looses out depending on how many characters you want. The more you want, the more they lose randomness.

They achieve it by limiting the amount of numbers possible preceding the fixed length.

So for instance, a random number of fixed length 2 would be 10 - 99. For 3, 100 - 999. For 4, 1000 - 9999. For 5 10000 - 99999 and so on. As can be seen by the pattern, it suggests 10% loss of randomness because numbers prior to that are not possible. Why?

For really large numbers ( 18, 24, 48 ) 10% is still a lot of numbers to loose out on.

function generate(n) {
        var add = 1, max = 12 - add;   // 12 is the min safe number Math.random() can generate without it starting to pad the end with zeros.   

        if ( n > max ) {
                return generate(max) + generate(n - max);
        }

        max        = Math.pow(10, n+add);
        var min    = max/10; // Math.pow(10, n) basically
        var number = Math.floor( Math.random() * (max - min + 1) ) + min;

        return ("" + number).substring(add); 
}

The generator allows for ~infinite length without lossy precision and with minimal performance cost.

Example:

generate(2)
"03"
generate(2)
"72"
generate(2)
"20"
generate(3)
"301"
generate(3)
"436"
generate(3)
"015"

As you can see, even the zero are included initially which is an additional 10% loss just that, besides the fact that numbers prior to 10^n are not possible.

That's now a total of 20%.

Also, the other options have an upper limit on how many characters you can actually generate.

Hardcore (lol):

generate(100000);

"0651381536751559954594864685266964793332464219914923661511711844396177002509535418334876544401924094917073213696256662736759171746155525355813820984082896909515404479432572083119349115959844601455002767695272126890943622034785199462903486615630903373736074650341933983047891115762996521811932187801517891301186904384726119762019718175435710932238346050607608330909038106079638907289974335424918916347390133250423195745981282871695914427143478015387526550643354556230557162085731499833124538228077899015387696795454233963829987328340703344884739850232366267319735437910316929832577036161160111766389779986306750540325053526332954707426521749319245685086246138852076226686592711423547069039829989359264378828053036717401113209577249028130393660800381824348578927107867412974551300511362724049498987060763708244949878691726303643609390144364016831976572032148916321330320693070018092909287513750833169369109704174178477032247944615585736953235426525770952182901723678094125452064709391262205505794896588467103839918798865986558164401714970627462474221512933182302681399770009238608569828198282594067031551589957066160459772535721218782628326984718480572065873099842295277633929431998644299592113453576385173567792887599814962391491057766181804686525454994535331956452351714080296349460787376377707332784374182769767491492626250695553656723782130680555136033698739748989110048095410831112923640685263942718951956051629868800760455527608163584040946391007996727804307183409133475760436780643452539625346136429684905697101047939193048590914919878829383906351337053184913823008300679694028703685623727771499860247737932264827173466218593294990480640551139122803223625353361708900123038017780047641220235742349899490580373913548466797570492357261650370416581586068946910750746456272020039989451556990958758038936686950664094355266620153834909274865405514128481190933769790743330654469775143510701067073238592791899235626861196974193363925127586730787377648334892346319583406971304451718976145383072306413469155987486447356622988426019558465431875505538702558565347559580202646849041387156283262505660125997956398869698806508328747714519622979932186678894485401315173760703884808651627289565546642595836542685648986064356954101696992288261891697786208558024710704710569276399395840580530230729718025713461618331061135991512805033299376252465571484999555923213609948515733572046075843375936972718778384464568891829113564444707717097719585207988502346513167888955683555484353510332395153755395909821566281989562081559052296158702137775090530683411921904165289066506048057826656008626549349520988632955599817667026102612246900688687033297726679175137756611576660839769713756589194642097257515032724723644287567807024460903027237918875450869621587384055399117177199561406778632097959377881722104757305489848832281818424422232658544588293086904471013832617620773148176645007693759497261239127503209456938874072938525618495608073774801776586228941306687157603648217719830741573207094853490260210457990217605600170536198504037929712676654872110771920253815273483354540963203021459754583032672211518949520939438225644651968189817072011400396165500599785252339489882056244086137573020347521044405459170093723855104182434230586691062441396739135676667876492508103316749255705804685196457776485441020566127708427354576129440946667137723266039252799238436908929664871559917271173890952501649969845323228911324304676033091791915543087040187338337985765900657501913326852341426754081753024526806628074157361061567145719925513947877710209406336870076364803110885165116889134514669440038093239844794417558222940044136681059927679868309962907439502915297704409286220631579548570846901779646252916735446700599319216127956590498537500296871549698551487524694730938334435602147792823774342018907256300973661332969751774453467754551030776244984673134327042549212346064016972266244421350446816023749761725326179725773631423251263241676364878077179121265520596533163857823832473659397459170863496209471969573015681099162917804608615592702751630859496460179021996381923016837765373971029344070259758032878342631664623233278865516293215903319598262833063285069029198481899370947051648391946052895356840798550825719722336591850778627364466574843889148095773261912719117480110491748466533525498678000253654834894959160056255689033940722775415886473011808596999471244206729824146278357431053778299946416560280321553991926322558288133660604761058885313628667565782057669777245228782157232415565470266425379986471558087623005877735347590673298523682042211654895539684959898310428673791086684470635130006701184979952716864452222287796185706873800126958417574002714651197052304976945291998261929510003409823301738163131184044321814967421948738077959973418977062820073272801871097791663304563677054446929522613820657158036044974077149068042264275041629991352453921603299417152412504283176126310892490074417066376036263139046485941308078474763782335271468941107500031402589191940264394201058998139384015586420043812700974998994846862783848323459027436711834029982961475394883663440929202466261118224034811753878675892626850000745927102030593859984871338541236857940137673923872330726491463521617428477728693077627246150789224577503974195294720010681235567512991787544000684873076367225265005980170732582210349335893572411614183693449732342550786984026709335344882368848483689841098289521520159842810020191403158597931892038675563703040339560051072485874177869853627258620119850024839239790991752234985493282886483878099220884607098541461828163062036559320051850664311787732545443545872718896705693074322491654059388337598948684563099349286348837258695198691715548293085118800469279568611247763603333212769696312930202331209719311698010959089495486686416701141580902003477739022656317482105542147788152780612039330285858045010109725749512856294226929278452910769275369968190680868822708154750824134942359214079088522653031930479967950106001756666750685834781326854966710709199027624399171678838338771888827826988895147799981407964765904933894198041473605722426155926472549738623915695131607125663472416755760625877192413222392834744760573194698174184828593952615330008182973235328807832466170477548637589334335253898665521398464526370554264342147842986253786980578314778173661019148173130327119873408737701145928515500658351289473328456285583253571413960151165721809937639271102772177604114259723504396074043857324876347952792500778241101315813932920875678857323985024397013308505439799092690329997846663211646708116890679317619633523367148203786872452797721688341649265556212929572302923254328310433097096422518332461522238314853608672131157398326333086636637710579603406236531242797001572404086121679806710619791401430723164752984010278279527256729659512285551846346525670396866491305030366052611420386629486883742338601295651738388001697647924588031892981500198791375362752776720252588049589262755602871270846735355848074534250430763842450204908016408980427882039831985645664399270103577548870120224819919262753016026165808042161240890128034530862386797980786530084995404258139393926242285856891852536101388461974355122811586411039593712363708990011716527704724695088670655140918478826975809560414499747323017065409019926404257362977641295374223246846824885957539038318366351775694121202206592027411031573694626783792527141205298171742811339736677829523571328298430978526492030270747840488062983567775807783758303942162746481495259894565800433588989148287828612636489953375970590336691568227027250830962451881414054532701394664621643793652659730680829782628228533496535022066254538114154750886394448619560557056090587134817765243336371995254731768578145789253081136781165232380981423661461947317624294565206639212050765935523252915568678332631643661404278947432925525662760688013716440760830951338977985068158333504142195975491474394784277375073913171986990582377987023788932860558988769345591421822956624611110395013648711595243092167162020435947799592249978899534215342536996693915479765219927236896875556418267953719666490566732043716962547762237949421980714168709049490782347854273531992819487089637953124284492758086703224352349743348457604761120733409407717030341936948166853948143433242252140863374400359359761306266558395167990712458271078696248819889876229262161656199388341741768515442688241996127565496982533125451938994200226802615272999244312311281180370991298113648307050761656528609111812818519937597989922582427406685845913968542758447240615610624851445680816432319237536466841678179826977061228472796341277749096815972710109141682142923221418300450889934793361752715170330903172203575743719842447552642209440935449303895937582103292344361773281904368852083615740443913930404143052760843333064898204276312372739440829872940436919768751089890247967337557653562879210163728376116079743767005431076841670441616652665636336229550601719325531779966031352898173391372064414093596851879022083272185840692660572194149639642073309095345114511750926138263623153925334192615658113833269237719526076431286320367730048784895945420614793303331120250754465511943883123584365330780388472745790546717486883844283359421247664497558319269087934420398659762073298209204864293120280646068964392658934917828520101658351360993611025135958090490678870508638473725333080789384783828962965033309159983224373031664875078140446422895304505649225445555564873856083488629044065544170858400698317145852209331837824336681551495069563493806386785704595613014667920738126365476692665159557868399438407300571627342425233751037082260963685748505556744991415176134639166352085172285172276758482154203549348712506151634474175365167098576444480905776241930649712981647594243229056955059691154745756909930548211510229291032212725487179388626117741684508226454916634024521067178497321754685991794920486377608095295314368866766826448127047221308873232277567988720647751988098042602089589821325908162267555756542692594698410032948436350206444474395792832337255903951405061202830201036008511147760724244082408881240159333112973046604988816375803715603929856334309755065"

generate(100000).length === 100000 -> true

More generally, generating a random integer with fixed length can be done using Math.pow:

var randomFixedInteger = function (length) {
    return Math.floor(Math.pow(10, length-1) + Math.random() * (Math.pow(10, length) - Math.pow(10, length-1) - 1));
}

To answer the question: randomFixedInteger(6);

I would go with this solution:

Math.floor(Math.random() * 899999 + 100000)
100000 + Math.floor(Math.random() * 900000);

will give a number from 100000 to 999999 (inclusive).

Based on link you've provided, right answer should be

Math.floor(Math.random()*899999+100000);

Math.random() returns float between 0 and 1, so minimum number will be 100000, max - 999999. Exactly 6 digits, as you wanted :)

I created the below function to generate random number of fix length:

function getRandomNum(length) {
    var randomNum = 
        (Math.pow(10,length).toString().slice(length-1) + 
        Math.floor((Math.random()*Math.pow(10,length))+1).toString()).slice(-length);
    return randomNum;
}

This will basically add 0's at the beginning to make the length of the number as required.

I was thinking about the same today and then go with the solution.

var generateOTP = function(otpLength=6) {
  let baseNumber = Math.pow(10, otpLength -1 );
  let number = Math.floor(Math.random()*baseNumber);
  /*
  Check if number have 0 as first digit
  */
  if (number < baseNumber) {
    number += baseNumber;
  }
  return number;
};

Let me know if it has any bug. Thanks.

"To Generate Random Number Using JS"

console.log(
Math.floor(Math.random() * 1000000)
);
<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Math.random()</h2>

<p id="demo"></p>

</body>
</html>

This is another random number generator that i use often, it also prevent the first digit from been zero(0)

  function randomNumber(length) {
    var text = "";
    var possible = "123456789";
    for (var i = 0; i < length; i++) {
      var sup = Math.floor(Math.random() * possible.length);
      text += i > 0 && sup == i ? "0" : possible.charAt(sup);
    }
    return Number(text);
  }

This code provides nearly full randomness:

function generator() {
    const ran = () => [1, 2, 3, 4, 5, 6, 7, 8, 9, 0].sort((x, z) => {
        ren = Math.random();
        if (ren == 0.5) return 0;
        return ren > 0.5 ? 1 : -1
    })
    return Array(6).fill(null).map(x => ran()[(Math.random() * 9).toFixed()]).join('')
}

console.log(generator())

This code provides complete randomness:

function generator() {

    const ran1 = () => [1, 2, 3, 4, 5, 6, 7, 8, 9, 0].sort((x, z) => {
        ren = Math.random();
        if (ren == 0.5) return 0;
        return ren > 0.5 ? 1 : -1
    })
    const ran2 = () => ran1().sort((x, z) => {
        ren = Math.random();
        if (ren == 0.5) return 0;
        return ren > 0.5 ? 1 : -1
    })

    return Array(6).fill(null).map(x => ran2()[(Math.random() * 9).toFixed()]).join('')
}

console.log(generator())

  var number = Math.floor(Math.random() * 9000000000) + 1000000000;
    console.log(number);

This can be simplest way and reliable one.

For the length of 6, recursiveness doesn't matter a lot.

function random(len) {
  let result = Math.floor(Math.random() * Math.pow(10, len));

  return (result.toString().length < len) ? random(len) : result;
}

console.log(random(6));

Here is my function I use. n - string length you want to generate

function generateRandomNumber(n) {
  return Math.floor(Math.random() * (9 * Math.pow(10, n - 1))) + Math.pow(10, n - 1);
}

parseInt(Math.random().toString().slice(2,Math.min(length+2, 18)), 10); // 18 -> due to max digits in Math.random

Update: This method has few flaws: - Sometimes the number of digits might be lesser if its left padded with zeroes.

You can use this module https://www.npmjs.com/package/uid, it generates variable length unique id

uid(10) => "hbswt489ts"
 uid() => "rhvtfnt" Defaults to 7

Or you can have a look at this module https://www.npmjs.com/package/shortid

const shortid = require('shortid');

console.log(shortid.generate());
// PPBqWA9

Hope it works for you :)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!