如何在java中将1200格式化为1.2k
我想用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
右边的数字为长或整数,左边的数字为字符串。 我应该如何处理这个问题。我已经为此做了一点算法,但我认为可能已经有一些发明出来了,在这方面做得更好,如果我开始处理数十亿和万亿的数据,就不需要额外的测试:)
其他要求:
- 格式最多应包含4个字符
- 以上表示1.1k正常,11.2k不正常。7.8米也可以,19.1米不行。小数点前一位只能有小数点。小数点之前的两位数表示小数点之后的数字李>
- 不需要四舍五入。(附加k和m的数字更多的是模拟仪表,表示近似值,而不是精确的逻辑条款。因此舍入是不相关的,这主要是因为变量的性质,即使在查看缓存结果时,舍入也可以增加或减少几个数字。)李>
# 1 楼答案
这是一个适用于任何长值的解决方案,我发现它非常可读(核心逻辑在
format
方法的底部三行完成)它利用
TreeMap
找到合适的后缀。令人惊讶的是,它比我以前编写的使用数组的解决方案更高效,而且更难阅读测试代码
# 2 楼答案
当前答案的问题
Java解决方案
这个解决方案(对this answer的扩展)解决了上述问题
常规解决方案
该解决方案最初是用Groovy编写的,如下所示
测试(Groovy)
这些测试是用Groovy编写的,但可以用来验证Java或Groovy类(因为它们都有相同的名称和API)
# 3 楼答案
这里有一个利用DecimalFormat的工程符号的解决方案:
输出:
# 4 楼答案
我的功能转换大到小的数字(2位)。您可以通过在
DecimalFormat
中更改#.##
来更改位数测试
希望能有所帮助
# 5 楼答案
需要一些改进,但是:快来营救吧
你可以把后缀放在一个字符串或数组中,然后根据功率或者类似的东西获取它们
部门也可以围绕权力进行管理,我认为几乎所有事情都与权力价值有关。 希望有帮助
产出:
# 6 楼答案
我知道,这看起来更像一个C程序,但它是超轻量的
它输出: