Prefix an Integer using JavaScript

While formatting numbers, prefixing an integer is a common operation. For example: If you have the 79, but you want to make it five digits always, just prefix it with three zeros – so it becomes 00079.

Let’s see how simple it is to prefix an integer in JavaScript. This script was originally shared by a programmer tobytai

<head>
<title>Prefix Integers with Zeros - DevCurry.com</title>
<script type="text/javascript">
function PrefInt(number, len) {
   return (Array(len).join('0') + number).slice(-length);
}
document.writeln(PrefInt(79, 4));
</script>
</head>

The OUTPUT is 00079.

If you are not familiar how the Slice() function works, check my article Slice() and Splice() in JavaScript




About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

1 comment:

Anonymous said...

I do not see why do we need here slice(-length). It is working without slicing because join return a string anyway.