Skip to content

Instantly share code, notes, and snippets.

@gburd
Created July 10, 2012 20:25
Show Gist options
  • Save gburd/3086007 to your computer and use it in GitHub Desktop.
Save gburd/3086007 to your computer and use it in GitHub Desktop.
Formatting numbers in JavaScript
function abbreviate_number(num)
{
var sizes = ['', 'thousand', 'million', 'billion', 'trillion', 'quadrillion', 'quintillion', 'sextillion', 'septillion'];
if (num < 1000) return num;
var i = parseInt(Math.floor(Math.log(num) / Math.log(1000)));
return ((i == 0) ? (num / Math.pow(1000, i)) : (num / Math.pow(1000, i)).toFixed(1)) + ' ' + sizes[i]; // use .round() if you don't want the decimal
};
bits_per = {
"KiB": 1024,
"MiB": 1048576,
"GiB": 1073741824,
"TiB": 1099511627776,
"EiB": 1152921504606846976,
"ZiB": 1180591620717411303424,
"YiB": 1208925819614629174706176
};
/**
* Convert number of bytes into human readable format
*
* @param integer bytes Number of bytes to convert
* @return string
*/
function format_bytes(bytes) {
var sizes = ['bytes', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB'];
if (bytes == 0) return '';
if (bytes == 1) return '1 byte';
var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
return ((i == 0)? (bytes / Math.pow(1024, i)) : (bytes / Math.pow(1024, i)).toFixed(1)) + ' ' + sizes[i]; // .round
};
function format_number(str)
{
str += '';
x = str.split('.');
x1 = x[0];
x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
return x1 + x2;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment