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

1 comment:

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

    ReplyDelete