Let's abbreviate those numbers! Now reverse?

PHP, 234 224 213 201 205 bytes

for(;$x=$argv[++$n];){$y=str_replace(",","",$x)/1e3;for($i=0;$y>999;$i++)$y=($y|0)/1e3;echo(A<$c=substr($x,strlen($x)-1))?number_format($x*[k=>1e3,m=>1e6,b=>1e9][$c]):($i?($y*10|0)/10:$y).kmb[$i]," ";}

6 bytes saved by insertusernamehere, 4 bytes inspired by that.


  • takes input from command line arguments, prints results space-separated with a trailing separator
  • expects lower case abbreviation
  • run with -r

-2 bytes if underscore as separator is ok: Replace " " with _.
-1 byte if correct rounding is ok: Replace ($y*10|0)/10 with round($y,1).
-17 bytes for PHP 7.1: Replace substr($x,strlen($x)-1) with $x[-1].


80 (63) bytes for expanding one argument only:

<?=number_format(($x=$argv[1])*[K=>1e3,M=>1e6,B=>1e9][substr($x,strlen($x)-1)]);

save to file, then execute (or replace <?= with echo +space and run with -r.


JavaScript, 545 524 522 518 514 508 504 498 494 214 bytes

Thanks to @ETHproductions for saving 180 bytes!

d=F=>F.map(f=>1/f.slice(-1)?f=(f=f.replace(/,/g,""))[9]?(f/1e8|0)/10+"B":f[6]?(f/1e5|0)/10+"M":f/1e3+"k":R(R(f.slice(0,-1)+"e"+' kMB'.indexOf(f.substr(-1))*3-0+"").match(/.{1,3}/g)+""),R=x=>[...x].reverse().join``)

To call the function:

d(["1.5M","1,500,000"]) //["1,500,500","1.5M"]

Outputs as alert, where each alert contains a different element of the input

Readable version:

d = F => F.map(f => 1 / f.slice(-1) ? f = (f = f.replace(/,/g, ""))[9] ? (f / 1e8 | 0) / 10 + "B" : f[6] ? (f / 1e5 | 0) / 10 + "M" : f / 1e3 + "k" : R(R(f.slice(0, -1) + "e" + ' kMB'.indexOf(f.substr(-1)) * 3 - 0 + "").match(/.{1,3}/g) + ""), R = x => [...x].reverse().join ``)

Summary of edits: converted function to an arrow function

  • removed semi-colons ';'
  • removed var
  • converted to an arrow function
  • used map to iterate through the individual elements of the array
  • used |0 instead of floor
  • used regex for testing
  • used ternary operators instead of if-else statements
  • included a separate function for .reverse().join''

Tags:

Code Golf