Introduction:
Like Twitter and Instagram and others, I wanted to display numbers like 1.2K
and 3.8 M
instead of 1,222
or 3,823,456
.
But that's not all! As we all know, there might be some human beings which undoubtely won't like these abbreviations and will try to reverse them. So, 1.2k
will become 1,200
and 3.8 M
will become 3,800,000
.
The task:
- your task is to write a program or a function that converts a list of numbers (which are given as strings) into their abbreviate pairs and vice-versa.
For example, if the input list (or any STDIN
) was ['1.4k', '1,234,567', '7.99M']
, then you should output:
['1,400', '1.2M', '7,990,000']
You can follow the next schema for abbreviations:
- 103 -> one kilo -> K
- 106 -> one million -> M
- 109 -> one billion -> B
Your code may assume all lowercase, all uppercase, mixed case or undefined case for input and use any of these for output, but should be consistent.
Rules and restrictions:
- you may write a program or function, taking input via
STDIN
(or closest alternative), command-line argument or function argument and outputting the result viaSTDOUT
(or closest alternative), function return value or function (out) parameter. - input may be in any convenient list or string format. You may assume that the
ai
are less than231
each and that the list contains at least one element. - each abbreviated number will contain only one
.
while a normal number will contain as many,
as necessary (you may assume that this numbers won't be altered). - you MAY NOT enter a number as
'123456'
but rather123,456
- standard code-golf rules apply.
Test cases:
Input: ['1.5M', '77.6k', '123,456,789'] Output: ['1,500,000', '77,600', '123.4M']
Input: ['3,000,000,000', '581k', '2b'] Output: ['3B', '581,000', '2,000,000,000']
Input: ['0.1k'] Output: ['100']
Input: ['888', '33'] Output: ['0.888k', '0.033k']
Clarifications:
- for numbers < 1000 after the decimal point in abbreviation output you should have as many digits as required to get the correct result. (e.g:
2
-> will become0.002k
) - that means 3 decimals at most; for numbers > 1000 you can have a maximum of 1 decimal. - the abbreviation may be in both lower or upper case
- I removed the built-ins restriction as suggested in the comments
The shortest code in bytes wins!
'123,456,789' -> '123.4M'
? Also, this doesn't clarify how many decimals to use. Surely anything under 1000 shouldn't need to be abbreviated anyways. \$\endgroup\$["k", "M", "G"]
. What does "while a normal number will contain as many , as necessary" mean, in my country it would be a mistake to use any. \$\endgroup\$