Relative Value (1K, 1M...)

Run Settings
LanguageJava
Language Version
Run Command
class Main { public static void main(String[] args) { System.out.println(relativeValue(7)); System.out.println(relativeValue(56)); System.out.println(relativeValue(125)); System.out.println(relativeValue(1025)); System.out.println(relativeValue(14029)); System.out.println(relativeValue(235003)); } public static String relativeValue(int number) { // Thanks to https://stackoverflow.com/a/40774675 String[] suffix = new String[]{"K","M","B","T"}; int size = (number != 0) ? (int) Math.log10(number) : 0; if (size >= 3){ while (size % 3 != 0) { size = size - 1; } } double notation = Math.pow(10, size); double value = (size >= 3) ? (Math.round((number / notation) * 100) / 100.0d) : number; String strReturn = value + ""; strReturn = strReturn.contains(".") ? strReturn.replaceAll("0*$","").replaceAll("\\.$","") : strReturn; return (size >= 3) ? strReturn + suffix[(size/3) - 1] : strReturn; } }
Editor Settings
Theme
Key bindings
Full width
Lines