Skip to content

Instantly share code, notes, and snippets.

@cmonaghan
Created January 19, 2014 02:19
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 cmonaghan/8499612 to your computer and use it in GitHub Desktop.
Save cmonaghan/8499612 to your computer and use it in GitHub Desktop.
Here is a simple way to convert large numbers into an easily readable string. This is useful for displaying large numbers to the user. For example: 200000 --> "200k" 1200000 --> "1.2M" 54100000000 --> "54.1B"
var readifyNumbers = function(number) {
/* READIFYNUMBERS ASSUMPTIONS:
- Numbers will have typeof number or string
- No commas (expects format to be: 1500000)
*/
// throw error for any parameter input that is not a number and cannot be converted into a number
if (Number(number).toString() === 'NaN') {
throw 'Error. The readifyNumbers input parameter must be a number.';
}
// convert input number to string and remove anything after the decimal
var numberString = Math.floor(number).toString();
// find digits length
var digitsLength = numberString.length;
// check length (to determine whether to convert to thousands or millions)
if (digitsLength <= 3 && digitsLength !== 0) {
return trimToTenths( number.toString() );
} else if (digitsLength <= 6) {
number = number/1000;
return trimToTenths( number.toString() ) + 'k';
} else if (digitsLength <= 9) {
number = number/1000000;
return trimToTenths( number.toString() ) + 'M';
} else if (digitsLength <= 12) {
number = number/1000000000;
return trimToTenths( number.toString() ) + 'B';
} else {
console.log('Only numbers with a string length between 1-12 digits before the decimal will be converted to a readable number.');
return number.toString();
}
// helper functions
function trimToTenths(stringifiedNumber) {
var index = stringifiedNumber.indexOf('.');
if (index === -1) {
return stringifiedNumber;
} else {
var slicedNum = stringifiedNumber.slice(0, index + 3); // slices an extra digit so that it can be rounded
var roundedNum = Math.round(Number(slicedNum) * 10) / 10; // multiply, then divide by 10 as a quick hack to round to the tenths place
return roundedNum.toString();
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment