Skip to content

Instantly share code, notes, and snippets.

@tobiasroeder
Last active May 15, 2023 13:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tobiasroeder/720ee191eadaac5b3cdb5ee02dc1776e to your computer and use it in GitHub Desktop.
Save tobiasroeder/720ee191eadaac5b3cdb5ee02dc1776e to your computer and use it in GitHub Desktop.
Turn a one digit number into a two digit number string.
/**
* 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