Created
June 24, 2018 14:50
-
-
Save namcoder/1fa2e3088b72cca36a9b58e3677bdcc9 to your computer and use it in GitHub Desktop.
Add Zero before number less than 10
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
('0' + 11).slice(-2) // '11' | |
('0' + 4).slice(-2) // '04' | |
For ease of access, you could of course extract it to a function, or even extend Number with it: | |
Number.prototype.pad = function(n) { | |
return new Array(n).join('0').slice((n || 2) * -1) + this; | |
} | |
Which will allow you to write: | |
c += deg.pad() + '° '; // "04° " | |
The above function pad accepts an argument specifying the length of the desired string. If no such argument is used, it defaults to 2. You could write: | |
deg.pad(4) // "0045" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment