java long 1 000_如何在Java中将1200格式化为1.2k

小编典典

这是一个适用于任何长值的解决方案,并且我觉得它很可读(核心逻辑在方法的底部三行中完成format)。

它利用它TreeMap来找到合适的后缀。它比我以前写的使用数组的解决方案效率更高,读起来更困难。

private static final NavigableMap 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 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);

}

}

2020-03-21

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值