0

is there any way to make a number shorter? For example like 1.000.000 into 1M, 1.000 to 1k, 10.000 to 10k, and so on

heagan
  • 31
  • 8
  • 1
    This might help you : https://stackoverflow.com/questions/2685911/is-there-a-way-to-round-numbers-into-a-reader-friendly-format-e-g-1-1k – Harshana Dec 03 '20 at 11:36

3 Answers3

0

If you are using a js library or framework (such as angular,react), you can use this

number-abbreviate

fahimchowdhury
  • 424
  • 4
  • 8
0

Try something like this:

function fnum(x) { if(isNaN(x)) return x;

if(x < 9999) {
    return x;
}

if(x < 1000000) {
    return Math.round(x/1000) + "K";
}
if( x < 10000000) {
    return (x/1000000).toFixed(2) + "M";
}

if(x < 1000000000) {
    return Math.round((x/1000000)) + "M";
}

if(x < 1000000000000) {
    return Math.round((x/1000000000)) + "B";
}

return "1T+";

}

axysharma
  • 113
  • 1
  • 8
0

You could try something like this:

function shortenNum(num, decimalDigits) {
  if (isNaN(num)) {
    console.log(`${num} is not a number`)
    return false;
  }

  const magnitudes = {
    none: 1,
    k: 1000,
    M: 1000000,
    G: 1000000000,
    T: 1000000000000,
    P: 1000000000000000,
    E: 1000000000000000000,
    Z: 1000000000000000000000,
    Y: 1000000000000000000000000
  };

  const suffix = String(Math.abs(num)).length <= 3 ?
    'none' :
    Object.keys(magnitudes)[Math.floor(String(Math.abs(num)).length / 3)];

  let shortenedNum
  if (decimalDigits && !isNaN(decimalDigits)) {
    const forRounding = Math.pow(10, decimalDigits)
    shortenedNum = Math.round((num / magnitudes[suffix]) * forRounding) / forRounding
  } else {
    shortenedNum = num / magnitudes[suffix];
  }

  return String(shortenedNum) + (suffix !== 'none' && suffix || '');
}

// tests
console.log('1:', shortenNum(1));
console.log('12:', shortenNum(12));
console.log('198:', shortenNum(198));
console.log('1278:', shortenNum(1278));
console.log('1348753:', shortenNum(1348753));
console.log('7594119820:', shortenNum(7594119820));
console.log('7594119820 (rounded to 3 decimals):', shortenNum(7594119820, 3));
console.log('7594119820 (invalid rounding):', shortenNum(7594119820, 'foo'));
console.log('153000000:', shortenNum(153000000));
console.log('foo:', shortenNum('foo'));
console.log('-15467:', shortenNum(-15467));
console.log('0:', shortenNum(0));
console.log('-0:', shortenNum(-0));
secan
  • 2,622
  • 1
  • 7
  • 24