我想用java将以下数字格式化为它们旁边的数字:
1000 to 1k 5821 to 5.8k 10500 to 10k 101800 to 101k 2000000 to 2m 7800000 to 7.8m 92150000 to 92m 123200000 to 123m
右边的数字将是long或整数,而左边的数字将是字符串。我应该如何处理。我已经为此做了很少的算法,但是我认为可能已经发明了一些更好的方法,并且如果我开始处理数十亿和数万亿,则不需要额外的测试:)
其他要求:
这是一个适用于任何长值的解决方案,并且我觉得它很可读(核心逻辑在方法的底部三行中完成format)。
format
它利用它TreeMap来找到合适的后缀。它比我以前写的使用数组的解决方案效率更高,读起来更困难。
TreeMap
private static final NavigableMap<Long, String> suffixes = new TreeMap<> (); static { suffixes.put(1_000L, "k"); suffixes.put(1_000_000L, "M"); suffixes.put(1_000_000_000L, "G"); suffixes.put(1_000_000_000_000L, "T"); suffixes.put(1_000_000_000_000_000L, "P"); suffixes.put(1_000_000_000_000_000_000L, "E"); } public static String format(long value) { //Long.MIN_VALUE == -Long.MIN_VALUE so we need an adjustment here if (value == Long.MIN_VALUE) return format(Long.MIN_VALUE + 1); if (value < 0) return "-" + format(-value); if (value < 1000) return Long.toString(value); //deal with easy case Entry<Long, String> e = suffixes.floorEntry(value); Long divideBy = e.getKey(); String suffix = e.getValue(); long truncated = value / (divideBy / 10); //the number part of the output times 10 boolean hasDecimal = truncated < 100 && (truncated / 10d) != (truncated / 10); return hasDecimal ? (truncated / 10d) + suffix : (truncated / 10) + suffix; }
测试码
public static void main(String args[]) { long[] numbers = {0, 5, 999, 1_000, -5_821, 10_500, -101_800, 2_000_000, -7_800_000, 92_150_000, 123_200_000, 9_999_999, 999_999_999_999_999_999L, 1_230_000_000_000_000L, Long.MIN_VALUE, Long.MAX_VALUE}; String[] expected = {"0", "5", "999", "1k", "-5.8k", "10k", "-101k", "2M", "-7.8M", "92M", "123M", "9.9M", "999P", "1.2P", "-9.2E", "9.2E"}; for (int i = 0; i < numbers.length; i++) { long n = numbers[i]; String formatted = format(n); System.out.println(n + " => " + formatted); if (!formatted.equals(expected[i])) throw new AssertionError("Expected: " + expected[i] + " but found: " + formatted); } }