How to output leading 0's on output of a number variable?

How to output leading 0's on output of a number variable?

6,686585
Grand MasterGrand Master
6,686585

    Jun 10, 2010#1

    Simple script for understanding:

    Code: Select all

    var nLineNum = 0;
    var nLineCnt = 0;
    var sPrefix = "0000";
    
    nLineCnt = UltraEdit.getValue("How many lines to write?",1);
    
    while (nLineNum < nLineCnt)
    {
       var sLineNum = nLineNum.toString();
       UltraEdit.activeDocument.write("Line " + sPrefix.substr(sLineNum.length) + sLineNum + "\r\n");
       nLineNum++;
    }
    Explanation:

    var sPrefix = "0000"; defines the leading zeros for numbers 0 to 9999.

    var sLineNum = nLineNum.toString(); - conversion of the value of the number (in Javascript integer or float, in this example integer) to a string using the method toString() of the number object. Even an integer "variable" is in Javascript not a simple variable, it is a number object.

    sPrefix.substr(sLineNum.length) - the substr() method returns a substring of the string value of string object sPrefix starting from specified index (index count starts with 0) defined in the first parameter with n characters as defined in the second parameter. Omitting the second parameter as done here means everything to end of string. If the number has only 1 digit (0-9), 3 leading zeros are needed and therefore the zeros starting from index 1 are needed from prefix string. A 2 digits number needs 2 leading zeros and therefore 2 zeros from the prefix string, and so on.

    To always get correct output, check value of nLineCnt before starting the loop. A value greater than 9999 would result with this code in a wrong output.

    String value of sPrefix could be created dynamically based on value of nLineCnt as shown below.

    Code: Select all

    var nLineNum = 0;
    var nLineCnt = 0;
    var sOutput = "";
    var sPrefix = "0";
    
    nLineCnt = UltraEdit.getValue("How many lines are there?",1);
    
    // Please note that nResult can be a float after first division by 10. So don't
    // use nResult > 9 here because 99 / 10 = 9.9 and this is greater than 9.
    for (var nResult = nLineCnt; nResult >= 10; nResult /= 10 ) sPrefix += '0';
    
    while (nLineNum < nLineCnt)
    {
       var sLineNum = nLineNum.toString();
       sOutput += "Line " + sPrefix.substr(sLineNum.length) + sLineNum + "\r\n";
       nLineNum++;
    }
    if (sOutput.length) UltraEdit.activeDocument.write(sOutput);
    This script is also speed optimized. Instead of writing every line into active document, the entire output is build in memory and finally written as one string into the active document. So only 1 display update and also only 1 undo record.