Last active
August 29, 2015 14:02
-
-
Save bjmiller121/3c6fbca25571a94dce1b to your computer and use it in GitHub Desktop.
Simple function for parsing a number and creating a "pretty" formatted version such as 1.3k. Useful for things like social share counts.
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
| /** | |
| * Given a number or string, parses out the number and creates a "pretty" | |
| * rounded version. | |
| * | |
| * @param {Number|String} raw - string or number to parse | |
| * @return {Object} information about the passed number | |
| * - {Number} number - cleaned up integer | |
| * - {String} pretty - "pretty" formated number | |
| * - {Number} digits - number of digets | |
| */ | |
| function parseCount(raw) { | |
| number = parseInt(raw) > 0 ? parseInt(raw) : 0; | |
| var count = { | |
| number: number, | |
| pretty: number.toString(), | |
| digits: number.toString().length | |
| }; | |
| if (count.digits > 3 && count.digits < 7) { | |
| count.pretty = Math.floor(number/100)/10 + 'k'; | |
| } else if (count.digits > 7) { | |
| count.pretty = Math.floor(number/100000)/10 + 'm'; | |
| } | |
| return count; | |
| } | |
| // Examples: | |
| parseCount(89); // Object {number: 89, pretty: "89", digits: 2} | |
| parseCount('672'); // Object {number: 672, pretty: "672", digits: 3} | |
| parseCount(1328); // Object {number: 1328, pretty: "1.3k", digits: 4} | |
| parseCount(2398234); // Object {number: 2398234, pretty: "2.3m", digits: 7} | |
| parseCount('13098098289');// Object {number: 13098098289, pretty: "13098m", digits: 11} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment