Last active
May 15, 2023 13:01
-
-
Save tobiasroeder/720ee191eadaac5b3cdb5ee02dc1776e to your computer and use it in GitHub Desktop.
Turn a one digit number into a two digit number string.
This file contains 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
/** | |
* Turn a one digit number into a two digit number string. | |
* | |
* If you can not garantee that the number n is a number, simply wrap it with Number(n) to turn the string into a number. | |
* | |
* The following three functions are doing the same thing. You can choose which one fits the best purpose for you. The last one has the most legacy support. | |
*/ | |
/** | |
* Turn a one digit number into a two digit number string by using the padStart method. | |
* | |
* @param {number} n An integer. | |
* | |
* @returns {string} | |
*/ | |
function to2digits(n) { | |
return String(n).padStart(2, '0'); | |
} | |
/** | |
* Turn a one digit number into a two digit number string. | |
* | |
* @param {number} n An integer. | |
* | |
* @returns {string} | |
*/ | |
const to2digits = n => (n < 10 ? '0' + n : n); | |
/** | |
* Turn a one digit number into a two digit number string. | |
* | |
* @param {number} n An integer. | |
* | |
* @returns {string} | |
*/ | |
function to2digits(n) { | |
return n < 10 ? '0' + n : n; | |
} | |
/** | |
* Turn a one digit number into a two digit number string. | |
* | |
* @param {number} n An integer. | |
* | |
* @returns {string} | |
*/ | |
function to2digits(n) { | |
if (n < 10) { | |
return '0' + n; | |
} | |
return n; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment