public static String abbreviateInt ( Number number , int decPlaces ) { if ( number == null ) { return "" ; } String abbrevn = number . toString ( ) ; // 2 decimal places => 100, 3 => 1000, etc decPlaces = ( int ) Math . pow ( 10 , decPlaces ) ; // Enumerate number abbreviations String [ ] abbrev = { "K" , "M" , "B" , "T" } ; boolean done = false ; // Go through the array backwards, so we do the largest first for ( int i = abbrev . length - 1 ; i >= 0 && ! done ; i -- ) { // Convert array index to "1000", "1000000", etc int size = ( int ) Math . pow ( 10 , ( double ) ( i + 1 ) * 3 ) ; // If the number is bigger or equal do the abbreviation if ( size <= number . intValue ( ) ) { // 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 . intValue ( ) * decPlaces / ( float ) size ) / decPlaces ; // Add the letter for the abbreviation abbrevn = number + abbrev [ i ] ; // We are done... stop done = true ; } } return abbrevn ; }
Abbreviates an integer by adding a letter suffix at the end . E . g . M for millions K for thousands etc .