Skip to content

Instantly share code, notes, and snippets.

@vongillern
Created January 7, 2015 17:08
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 vongillern/5eddb2c2d75156bbf30d to your computer and use it in GitHub Desktop.
Save vongillern/5eddb2c2d75156bbf30d to your computer and use it in GitHub Desktop.
"Humanize" number for display in javascript
//humanize(493827444735) = '494B'
//humanize(49382744473.5) = '49B'
//humanize(4938274447.35) = '4.9B'
//humanize(493827444.735) = '494M'
//humanize(49382744.4735) = '49M'
//humanize(4938274.44735) = '4.9M'
//humanize(493827.444735) = '494K'
//humanize(49382.7444735) = '49K'
//humanize(4938.27444735) = '4.9K'
//humanize(493.827444735) = '494'
//humanize(49.3827444735) = '49.4'
//humanize(4.93827444735) = '4.94'
//humanize(0.493827444735) = '0.494'
//humanize(0.0493827444735) = '0.0494'
//humanize(0.00493827444735) = '0.00494'
//humanize(0.000493827444735) = '0.000494'
//humanize(0.0000493827444735) = '0.0000494'
function humanize(value) {
if (value >= 1000000000) {
var val = (value / 1000000000);
if (val.toFixed(1).length > 3)
return val.toFixed(0) + "B";
else
return val.toFixed(1) + "B";
}
if (value >= 1000000) {
var val = (value / 1000000);
if (val.toFixed(1).length > 3)
return val.toFixed(0) + "M";
else
return val.toFixed(1) + "M";
}
if (value >= 1000) {
var val = (value / 1000);
if (val.toFixed(1).length > 3)
return val.toFixed(0) + "K";
else
return val.toFixed(1) + "K";
}
if (value >= 100) {
return value.toFixed(0) +"";
}
if (value >= 10) {
return value.toFixed(1) +"";
}
if (value >= 1) {
return value.toFixed(2) +"";
}
if (value < 1 && value > 0) {
return value.toPrecision(3);
}
return value + "";
}
@mikauser001
Copy link

Nice function, very useful.

I'd add the following:

const valueConditionCheck = Math.abs(value);

Then I can check the conditions with abs to also include the negative side with your custom format, but return the value with the correct format.

Best

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment