In JavaScript, how would one write a function that converts a given [edit: positive integer] number (below 100 billion) into a 3-letter abbreviation -- where 0-9 an
For easy and direct you. Simply make a prototype of it. Here is an example.
Number.prototype.abbr = function (decimal = 2): string {
const notations = ['', 'k', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y'],
i = Math.floor(Math.log(this) / Math.log(1000));
return `${parseFloat((this / Math.pow(1000, i)).toFixed(decimal))}${notations[i]}`;
};