我想用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); } }