Skip to content

Instantly share code, notes, and snippets.

@sionjlewis
Last active August 29, 2015 14:22
Show Gist options
  • Save sionjlewis/ecac7be0002507ec7abe to your computer and use it in GitHub Desktop.
Save sionjlewis/ecac7be0002507ec7abe to your computer and use it in GitHub Desktop.
Prepend zeroes to a number
<span>Max num of zeros to pad by: </span><input id="numZeros" type="number" value="3" /><br />
<span>Enter your number: </span><input id="numInput" type="number" value="5" /><br />
<br />
<span>Output: </span><label id="lblOutput"></label><br />
<br />
<button id="btnSubmit" type="submit" onclick="javascript:SJL.click_Submit();return false;">Submit</button><br />

Prepend zeroes to a number ('-' * 26) Using JavaScript to prepend zeroes to a number, for example: 0005 instead of 5 or Using JavaScript to prepend zeroes to a number, for example: 0099 instead of 99.

A Pen by Siôn J. Lewis on CodePen.

License.

if (SJL === undefined || typeof (SJL) !== 'object') { var SJL = new Object(); }
SJL = function () {
var self = {};
// This funxtion does the work...
self.prependZeroes = function (str, maxLength) {
// Keep calling its self until the string length is meet.
return str.length < maxLength ? self.prependZeroes("0" + str, maxLength) : str;
}
// ------------------------------
self.click_Submit = function () {
var numInput = $('#numInput').val();
var numZeros = $('#numZeros').val();
var output = self.prependZeroes(numInput, numZeros);
$('#lblOutput').html(output);
}
return {
click_Submit: function () {
return self.click_Submit();
}
}
}();
span {
display:inline-block;
width:200px;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment