栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何在Java中将1200格式化为1.2k

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何在Java中将1200格式化为1.2k

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

format
)。

它利用它

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);  }}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/470597.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号