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

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

The OUTPUT is 00079.

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

Will you give this article a +1 ? Thanks in advance

About The Author

Suprotim Agarwal
Suprotim Agarwal, ASP.NET Architecture MVP (Microsoft Most Valuable Professional) works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He is the Editor of a Developer Magazine called DNC Magazine. He has also written two EBooks 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.