Vignesh Subramanian
Vignesh Subramanian

Reputation: 7289

for loop for 0 to n number with digits specification

How can I write a for loop for 16 digit number from 0 to n

I want the output to be like:

0000000000000000
0000000000000001
0000000000000002
0000000000000003
0000000000000004
0000000000000005

Tried this but this isn't working:

for(i = 0000000000000000; i < 0000000000000010; i++){
    $("#TestDiv").append(i);
}

check out the JSfiddle

Upvotes: 0

Views: 120

Answers (3)

Marko
Marko

Reputation: 10992

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
</head>
<body>

    <script>
        function writeNumber(n){
            var nLen = n.toString().length;
            var zeroLen = 16-nLen;
            var arr = [];
            var str = "0";
            for(var z=0;z<zeroLen;z++){
                arr.push(str);
            }
            arr.push(n.toString());
            return arr.join('');
        }

    window.onload = function () {


        var arr = [];
        for(i=0;i<11;i++){
            var str = writeNumber(i);
            arr.push(str);
        }

        document.getElementById("testDiv").innerHTML = arr.join('<br>');

    };

    </script>

    <div id="testDiv"></div>

</body>
</html>

More efficient with an array. Maybe it doesn't matter so much when the loop is just 10 items, but you're going to write to the DOM 10 times if you access the DOM inside the loop instead of outside the loop just 1 time. All the small things adds up, so it may matter.

9. Stop touching the DOM, damnit!

Upvotes: 1

Mritunjay
Mritunjay

Reputation: 25892

That won't work because for number 00000001 is equal to 1 . You've to use strings.

Use like bellow

var str = '';
var zeros = '0000000000000000'; //string of 16 0's
for(i=0;i<11;i++){
    var temp = zeros.slice(i.toString().length); // get the 0's 16-length of i
    str += temp+i+'<br>';
}

$("#TestDiv").append(str);

DEMO

Upvotes: 0

haxxxton
haxxxton

Reputation: 6442

Have a look at using the slice method. For example:

var addLeadingZeros = function(number){
    var str = "0000000000" + number; // add leading zeros for single digit number
    return str.slice(-10); // slice the whole number down from the end
}
for(var i = 0; i < 100; i++){
    $("#TestDiv").append(addLeadingZeros(i));
}

Upvotes: 3

Related Questions