Skip to content

Instantly share code, notes, and snippets.

@codeofsumit
Created April 17, 2023 08:15
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 codeofsumit/e0048048b0fa3027f270d44e93cece6f to your computer and use it in GitHub Desktop.
Save codeofsumit/e0048048b0fa3027f270d44e93cece6f to your computer and use it in GitHub Desktop.
/**
* this function will abbreviate a number to a string
* It's only for charts as it takes into account the label range
* and shortens accordingly.
*
* @param {Number} value
* @param {Number} min
* @param {Number} max
* @param {Number} minimumFractionDigits
* @param {Number} labelCount
* @returns {String}
*
*/
function abbreviateValueforChartLabels(value, min, max, minimumFractionDigits = 0, labelCount = 0) {
// calculate the range between min and max
const range = (max - min) / labelCount;
// if the value is between -1k and 1k or the range is below 1k, or the value is 0, return the number as a string
if ((Math.abs(value) < 1000 && range <= 1000) || value === 0) {
return value.toLocaleString('de-DE', { minimumFractionDigits });
}
// get sign of the value
const sign = Math.sign(value);
const absValue = Math.abs(value);
// define suffixes and calculate the log of the absValue
const suffixes = ['', 'k', 'M', 'G', 'T', 'P', 'E'];
const logValue = Math.log10(absValue);
// calculate the suffix index
const suffixIndex = Math.floor(logValue / 3);
// abbreviate the absValue
let abbreviated = absValue / Math.pow(10, 3 * suffixIndex);
// calculate the range adjusted to the suffix
const rangeAdjusted = range / Math.pow(10, 3 * suffixIndex);
// if the range adjusted is below one, calculate the number of decimals needed
if (rangeAdjusted < 1) {
const decimalsNeeded = Math.ceil(-Math.log10(rangeAdjusted));
abbreviated = abbreviated
.toFixed(decimalsNeeded)
.replace('.', ',')
.replace(/(\d+),0+$/, '$1');
} else {
// otherwise, round the absValue
abbreviated = Math.round(abbreviated);
}
// return the abbreviated value with the correct suffix and add the sign if negative
if (sign === -1) {
return `-${abbreviated.toString().replace('.', ',') + suffixes[suffixIndex]}`;
}
return abbreviated.toString().replace('.', ',') + suffixes[suffixIndex];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment