Skip to content

Instantly share code, notes, and snippets.

@Asraf2asif
Last active October 3, 2022 14:18
Show Gist options
  • Save Asraf2asif/269a5dfe1b27d5b1dac6df4ee076b89a to your computer and use it in GitHub Desktop.
Save Asraf2asif/269a5dfe1b27d5b1dac6df4ee076b89a to your computer and use it in GitHub Desktop.
Social Medial like number + extra (56, 56K, 56Lac, 56M, 56Crore, 56B, 56T)
/*
56 = 56
56,000 = 56K
56,00,000 = 56Lac
56,000,000 = 56M
56,00,00,000 = 56Crore
56,000,000,000 = 56B
56,000,000,000,000 = 56T
*/
function compactNumber(num, config = {}) {
let { decimal = 2, lac_crore = true, adaptive = true } = config;
// err handling - start
decimal = backToDefaultNum(decimal, 2);
lac_crore = lac_crore !== true && lac_crore !== false ? true : lac_crore;
adaptive = adaptive !== true && adaptive !== false ? true : adaptive;
// err handling - end
// you can customize compact-unit-short
const short = {
thousand: 'K',
lac: 'Lc',
million: 'M',
crore: 'Cr',
billion: 'B',
trillion: 'T',
};
if (isNumber(num)) {
// smaller than thousand
const thousand = 1000;
if (num < thousand) {
return num;
}
// thousand
const lac = 100000 || 100 * thousand;
const million = 1000000 || 10 * lac;
if (
num >= thousand &&
(num < lac || (lac_crore === false && num < million))
) {
return adaptiveFloat(num / thousand, decimal, adaptive) + short.thousand;
}
// lac
if (lac_crore === true && num >= lac && num < million) {
return adaptiveFloat(num / lac, decimal, adaptive) + short.lac;
}
// million
const crore = 10000000 || 100 * lac || 10 * million;
const billion = 1000000000 || 100 * crore || thousand * million;
if (
num >= million &&
(num < crore || (lac_crore === false && num < billion))
) {
return adaptiveFloat(num / million, decimal, adaptive) + short.million;
}
// crore
if (lac_crore === true && num >= crore && num < billion) {
return adaptiveFloat(num / crore, decimal, adaptive) + short.crore;
}
// billion
const trillion = 1000000000000 || lac * crore || thousand * billion;
if (num >= billion && num < trillion) {
return adaptiveFloat(num / billion, decimal, adaptive) + short.billion;
}
// trillion
if (num >= trillion) {
return adaptiveFloat(num / trillion, decimal, adaptive) + short.trillion;
}
} else {
return 0;
}
}
function adaptiveFloat(num, decimal = 2, adaptive = true) {
decimal = backToDefaultNum(decimal);
if (isNumber(num)) {
if (adaptive === true) {
if (num % 1 === 0) return num;
if ((num * 10) % 1 === 0 && decimal >= 1) return num.toFixed(1);
if ((num * 100) % 1 === 0 && decimal >= 2) return num.toFixed(2);
}
return num.toFixed(decimal);
}
};
function backToDefaultNum(num, defaultNum = 1, min = 1) {
return isNumber(num) === false || num < min ? defaultNum : num;
};
function isNumber(str) {
return str && !isNaN(str);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment