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
Tweet
1 comment:
I do not see why do we need here slice(-length). It is working without slicing because join return a string anyway.
Post a Comment