Code-Golf: Acronym for Friendly Room

Based on this question: Is there a way to round numbers in a friendly format?

PROBLEM - UPDATED! (removed a hundred abbreviations from the specification)

The shortest code by the number of characters, which will reduce the integer (without decimals).

The code should include the full program.

The corresponding range is from 0 - 9,223,372,036,854,775,807 (upper limit for a signed 64-bit integer).

The number of decimal places for the abbreviation will be positive. You will not need to calculate the following: 920535 abbreviated -1 place (which would be like 0.920535M ).

Numbers in dozens and hundreds of places ( 0-999 ) should never be reduced (abbreviation for number 57 to 1+ decimal places 5.7dk - it is not needed and is not friendly).

Remember to round half from zero (23.5 rounds to 24). Bankers rounding - verboten.

The following are relevant abbreviations:

h = hundred (10 2 ) hit p>
k = thousand (10 3 )
M = million (10 6 )
G = billion (10 9 )
T = trillion (10 12 )
P = quadrillion (10 15 )
E = quintillion (10 18 )

SAMPLE INPUTS / OUTPUTS (inputs can be passed as separate arguments):

The first argument will be an integer to reduce. The second is the number of decimal places.

 12 1 => 12 // tens and hundreds places are never rounded 1500 2 => 1.5k 1500 0 => 2k // look, ma! I round UP at .5 0 2 => 0 1234 0 => 1k 34567 2 => 34.57k 918395 1 => 918.4k 2134124 2 => 2.13M 47475782130 2 => 47.48G 9223372036854775807 3 => 9.223E // ect... 



Original answer from a related question (JavaScript, not up to specification):

 function abbrNum(number, decPlaces) { // 2 decimal places => 100, 3 => 1000, etc decPlaces = Math.pow(10,decPlaces); // Enumerate number abbreviations var abbrev = [ "k", "m", "b", "t" ]; // Go through the array backwards, so we do the largest first for (var i=abbrev.length-1; i>=0; i--) { // Convert array index to "1000", "1000000", etc var size = Math.pow(10,(i+1)*3); // If the number is bigger or equal do the abbreviation if(size <= number) { // Here, we multiply by decPlaces, round, and then divide by decPlaces. // This gives us nice rounding to a particular decimal place. number = Math.round(number*decPlaces/size)/decPlaces; // Add the letter for the abbreviation number += abbrev[i]; // We are done... stop break; } } return number; } 
+27
language-agnostic code-golf number-formatting rosetta-stone human-readable
Apr 22 2018-10-22T00:
source share
9 answers

J, 61 63 65 characters

 ((j.&(1&{)":({.%&1e3{:));{&' kMGTPE'@{.)(([:<.1e3^.{.),{:,{.) 

Output:

 ((j.&(1&{)":({.%&1e3{:));{&' kMGTPE'@{.)(([:<.1e3^.{.),{:,{.) 1500 0 β”Œβ”€β”¬β”€β” β”‚2β”‚kβ”‚ β””β”€β”΄β”€β”˜ ((j.&(1&{)":({.%&1e3{:));{&' kMGTPE'@{.)(([:<.1e3^.{.),{:,{.) 987654321987654321 4 β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β” β”‚987.6543β”‚Pβ”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”˜ 

(The reason the output is β€œboxed” is similar to the fact that J does not support a list consisting of different types)

Explanation (from right to left):

(([:<.1000^.{.),{:,{.)

Create a new 3-element list, using , to join ([:<.1000^.{.) (Put <. Base 1000 log ^. Of the first parameter {. .. We attach it to the second parameter {: and then the first parameter {. ..

So, after the first bit, we converted the word 12345 2 to 1 2 12345

((j.&(1&{)":({.%&1000{:));{&' kMGTPE'@{.) uses ; to combine the two halves of an expression together in a field to get the final result.

The first half ((j.&(1&{)":({.%&1000{:)) , which divides ( % ) by the last input number ( {: by 1000, the first number of times. Then it sets the accuracy ": using the second number in the input list ( 1&{ ).

Second half {&' kMGTPE'@{. - the first number is used to select ( { ) the corresponding character from the list of abbreviations indexed 0.

+10
Apr 23 '10 at 17:08
source share

Python 2.x, 78 characters

 a=input() i=0 while a>=1e3:a/=1e3;i+=1 print"%g"%round(a,input())+" kMGTPE"[i] 

This version ( 75 characters ) uses printf, which will print extra zeros and follow the round-to-even rule.

 a=input() i=0 while a>=1e3:a/=1e3;i+=1 print"%%.%df"%input()%a+" kMGTPE"[i] 
+7
Apr 22 '10 at 18:40
source share

Javascript 114 characters

 function m(n,d){p=M.pow d=p(10,d) i=7 while(i)(s=p(10,i--*3))<=n&&(n=M.round(n*d/s)/d+"kMGTPE"[i]) return n} 

Also 114 - Using spidermonkey - Logging on to STDIN

 [n,d]=readline().split(' '),x=n.length,p=Math.pow,d=p(10,d) x-=x%3 print(Math.round(n*d/p(10,x))/d+" kMGTPE"[x/3]) 

104 - Function

 function(a,b,c,d){ c=(''+a).length; d=Math.pow; b=d(10,b); return((a*b/d(10,c-=c%3))+.5|0)/b+' kMGTPE'[c/3] } 

It also becomes 99 if you replace (''+a) with a and promise only to pass the lines :)

+5
Apr 22 '10 at 19:20
source share

Perl 114 111 104 characters

My first entry in the code room!

Arguments provided from standard input: perl fna.pl 918395 1

 ($n,$d)=@ARGV; @n=$n=~/./g; @s=' kMGTPE'=~/./g; printf"%.".(@n>3?$d:0)."f%s",$n/(10**($#n-$#n%3)),$s[@n/3]; 

Output:

918.4k




Golf version (with explanation):

 ( $number, $dp ) = @ARGV; # Read in arguments from standard input @digits = split //, $number; # Populate array of digits, use this to count # how many digits are present @suffix = split //, ' kMGTPE'; # Generate suffix array $number/(10**($#n-$#n%3)); # Divide number by highest multiple of 3 $precision = @n>3 ? $dp : 0; # Determine number of decimal points to print sprintf "%.".$precision."f%s", # "%.2f" prints to 2 dp, "%.0f" prints integer $number, $suffix[@n/3];# Select appropriate suffix 
+5
Apr 22 2018-10-22T00:
source share

Ruby - 79 77 75 83 characters

 n,d=ARGV l=n.to_s.length printf"%.#{l>3?d:0}f%s",n.to_f/10**(ll%3)," kMGTPE"[l/3] 

Reads from command line arguments.

74 72 80 characters, print the result in double quotes

 n,d=ARGV l=n.to_s.length p"%.#{l>3?d:0}f%s"%[n.to_f/10**(ll%3)," kMGTPE"[l/3]] 

66 74 characters, print extra zeros

 n,d=ARGV l=n.to_s.length p"%.#{d}f%s"%[n.to_f/10**(ll%3)," kMGTPE"[l/3]] 

Based on this solution and sample code.

+4
Apr 24 2018-10-10T00:
source share

dc - 75 characters

 A7 1:U77 2:U71 3:U84 4:U80 5:U69 6:U[3+r1-r]sJ?sddZd3~d0=Jrsp-Ar^ldk/nlp;UP 

Uses Z (number of digits) %3 to find the device. Most of the code is designed to set an array of unit characters, the actual code is 39 characters. Macro J set when %3 is 0 to avoid printing 0.918M in the 7th. precedent. It is not rounded properly.

If you say dc , feel free to improve it.

+3
Apr 23 '10 at 18:23
source share

PHP 57 chars

 for($a=num+1;$a>=1;$a=$a/26)$c=chr(--$a%26+65).$c;echo$c; 
+1
Jan 19 '11 at 9:03
source share

Haskell, 126 (without import, this is a function that takes two arguments):

 fnp|l>3=showFFloat (Just p) (cn/c 10^(lw)) [" kMGTPE"!!f]|True=show n where(f,w)=divMod l 3;c=fromIntegral;l=length$show n 

Expanded:

 import Numeric doit :: Integer -> Int -> String doit np | l > 3 = showFFloat (Just p) d [" kMGTPE" !! f] | otherwise = show n where d = (fromIntegral n) / fromIntegral (10^(lw)) (f,w) = divMod l 3 l = length $ show n 
+1
Oct 11 '12 at 18:35
source share

Perl 94 Chars

 ($_,$d)=@ARGV;$l=length;@u=' kMGTPE'=~/./g;printf"%.".($l>3?$d:0)."f$u[$l/3]",$_/10**($l-$l%3) 

Using:

 perl abbreviator.pl 47475782130 2 

Output:

 47.48G 
0
Jul 02 '10 at 12:37
source share



All Articles