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
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; }