开发者

Adding zeros when length is less

Is there a smart way to convert numbers to string and automatically add zeroes so the length is the same as the maximum?

like this:

for (va开发者_运维问答r i=0; i<30; i++) {
    var c = i.toString();
    if (c.length == 1) {
        c = '0'+=c;
    }
}

But smarter


There's a million ways, this is one of them, and its actually quite efficient too..

UPDATE 2 Here's code for the 'third interpretation of the OP's question

This will output ["00", "01", "02" .... ,"30"]

var max = 30, i = max, maxLength = max.toString().length, num,  zeroes=[];
while (i--) zeroes.push("0");
zeroes = zeroes.join();

for (i=0; i < max ; i++) {
    num = i.toString();
    console.log(zeroes.substring(0, maxLength - num.length) + num);
}

UPDATE 1 adapted the code for both 'possible' interpretations of the OP's question.

If what you want is code that based on n=5 , max = 30 produces 29 "0"s followed by "5" then this is the code you want

var n = 5, max = 30;

var a = n.toString().split(), zeroesToAdd = max - a.length;
while(zeroesToAdd--) a.unshift("0");
var num = a.join("");

alert(num);​

If what you want is code that based on n=5 , max = 30 produces 2 (the length of 30.toString()) "0"s followed by "5" then this is the code you want

var n = 5, maxLength = (30).toString().length;

var a = n.toString().split(), zeroesToAdd = maxLength - a.length;
while(zeroesToAdd--) a.unshift("0");
var num = a.join("");

alert(num);​

The only difference here is in the first line.

These do not use string concatenation (extremely inefficient), instead they use Array.unshift and Array.join


I think the fastest way to do it is without the loop. Like that:

var pad="000000";
var str="182"; //or any desired number here

var result=pad.slice(str.length)+str;

Result will be 000182. Let me know.

Michael


you could ask mr. google for a javascript implementation of sprintf() wich might be useful in some other cases - but if you only have to do this one operation, such a function will be a bit too much overhead.


I'm not entirely sure I understand what you mean by "smarter," but I did find this flexible zero-padding method (slightly modified due to @Sean's comment; in-code comments mine):

function PadDigits(n, totalDigits)
{
    n = n.toString();
    var pd = '';
    // Figure out if we need to pad at all
    if (totalDigits > n.length)
    {
        // Construct a string of as many leading zeroes as needed
        for (i = 0; i < (totalDigits-n.length); i++)
        {
            pd += '0'; // String concat for EACH leading zero; inefficient
        }
    }
    // Add the leading zeroes to the string representing the original number
    return pd + n; // Removed unnecessary toString() here
}

Source: http://classicasp.aspfaq.com/general/how-do-i-pad-digits-with-leading-zeros.html


for (var i=0; i<30; i++)
  var c = i < 10 ? '0'+i.toString() : i.toString() ;


var c=i.toString(), len=30-c.length;
while(len>0){
   c='0'+c;
   --len;
  }


var zeroPad = "000";

for(var i=0; i<30; i++) {
 var output = zeroPad + i.toString();
 output.substr(output.length - 2);
}

If you vary the number of "0" in zeroPad, and change your length offset, this will work for however large you want (obviously within reason). Not the best, but it works and is simple.


here is how to do it (parametric)

// number is the number you need to convert, and maxdigits is the total number of digits including the number
function leadingZeros( number, maxdigits )
{
 var number_text = number.toString();
 var number_len = number_text.length;

 for (var i=0;i<maxdigits-number_len;i++)
     number_text = '0'+number_text;

 return number_text;
}
// example leadingZeros(3,5)   will return 00003
// example leadingZeros(194,5) will return 00194


With courtesy from 4GuysFromRolla, for those used to VBScript:

var padd = "000000000000000000000000000000";
var sourceval = 100;

alert(Right(padd + sourceval, 30));

function Right(str, n)
{
    if (n <= 0)
    {
        return "";
    }

    if (n > String(str).length)
    {
        return str;
    }

    var iLen = String(str).length;
    return String(str).substring(iLen, iLen - n);
}


If you are trying to determine how many digits you will need, do a ceiling(log10) of the maximum number you are converting to a string, and that will tell you, assuming you don't have anything to the right of the decimal point.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜