Skip to content

Instantly share code, notes, and snippets.

@Anthodpnt
Last active December 13, 2016 16:09
Show Gist options
  • Save Anthodpnt/d7434dca124d162a34c6b529eb481972 to your computer and use it in GitHub Desktop.
Save Anthodpnt/d7434dca124d162a34c6b529eb481972 to your computer and use it in GitHub Desktop.
Formatting - Add Leading Zero
/**
* This gist is for Javascript beginners.
* @author: Anthony Du Pont <[email protected]>
* @site: https://www.twitter.com/JsGists
*
* You need sometimes to format you number and one of the common way to format them is to add a leading zero
* to numbers less than 10. There is many ways of doing this so let me show you some of them.
*
* Example:
* I have a number and I want to prepend a 0 to it if it's less than 10.
**/
// Long way
let num = 3;
if (num < 10) {
num = '0' + num; // Return `03`
}
// Short way
const numA = ('0' + 3).slice(-2); // Return `03`
const numB = ('0' + 10).slice(-2); // Return `10`
// Functional way
const numA = addLeadingZero(3); // Return `03`
const numB = addLeadingZero(10); // Return `10`
function addLeadingZero(number) {
return ('0' + number).slice(-2);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment