How can I get a string representation of a number with a certain number of characters, i.e. if the number is shorter, then add zeros first. For example: 5 -> '00005', 123 -> '00123'

    3 answers 3

    Something like this:

    var num = 135; var numF = addnull(num); console.log(numF); var num = 2; var numF = addnull(num); console.log(numF); function addnull(str) { str = str + ''; if (str.length < 5) { str = '0' + str; return addnull(str); } else { return str; }; } 

    • I also thought about something similar, but I hoped that there is a simpler way, like in Java for example))) - zonex5
    • with negative does not work. And that could have been the case - Sergiks

    Using the repeat function:

     if (!String.prototype.repeat) // полифил для repeat() String.prototype.repeat= function(count) { return new Array(count+1).join(this); }; var s= v.toString(); if(s.length<n) s= s[0]=='-'? '-'+'0'.repeat(ns.length)+s.substr(1) : '0'.repeat(ns.length)+s; 
    • one
      -9 => 000-9 - Sergiks
    • hmm, yes, now I will correct - sercxjo

     var num = 135; var numF = addnull(num); console.log(numF); var num = 2; var numF = addnull(num); console.log(numF); function addnull(str) { return ("0000" + str).substr(-5); } 

    • also for non - negative ones only - sercxjo