我想知道是否可以通过转换为2个小数位并添加后缀来格式化Java中的BigInteger格式?
E.g 1000 = 1.00k,1000000000000 = 1.00t
我目前正在使用以下代码,非常适合格式化longs ...
public static String withSuffix (long count) {
if (count < 1000) return "" + count;
int exp = (int) (Math.log(count) / Math.log(1000));
return String.format("%.2f %c", count / Math.pow(1000, exp), "kMBTab".charAt(exp-1));
}
有没有办法做这样的事情,但对于BigIntegers?
提前致谢!
答案 0 :(得分:0)
以下是格式化程序的示例:
String[] suffixes = { "€", "K", "M", "T"};
public final String format(BigInteger value) {
// As a string
String stringValue = value.toString();
// Packets are groups of three numbers
final List<String> packets = new ArrayList<>();
// Create packets
for (int i = stringValue.length(); 0 < i; i -= 3) {
if (i <= 3) {
packets.add(0, stringValue);
break;
}
packets.add(0, stringValue.substring(i - 3));
stringValue = stringValue.substring(0, i - 3);
}
// Create the number according to its length
final StringBuilder sb = new StringBuilder();
if (packets.size() > 1) {
sb.append(packets.get(0));
sb.append(".");
sb.append(packets.get(1).substring(0, 2));
sb.append(suffixes[packets.size()]);
} else {
System.out.println(packets.get(0) + "€");
return packets.get(0) + "€";
}
System.out.println(sb.toString());
return sb.toString();
}
它将BigInteger
格式化为String
,例如547.58T或0€。唯一的问题是它不能很好地支持负数。
答案 1 :(得分:0)
幸运的是,Maven Central 上有一个解决方案。
<dependency>
<groupId>com.github.bogdanovmn.humanreadablevalues</groupId>
<artifactId>human-readable-values</artifactId>
<version>1.0.1</version>
</dependency>
您可以只获取字节数或秒数的值。您也可以创建自己的分数类。
文档 https://github.com/bogdanovmn/java-human-readable-values
秒示例
assertEquals(
"2h 46m 40s",
new SecondsValue(10000).fullString()
);
assertEquals(
"2.8h",
new SecondsValue(10000).shortString()
);
字节示例
assertEquals(
"9K 784b",
new BytesValue(10000).fullString()
);
assertEquals(
"9.8K",
new BytesValue(10000).shortString()
);
自定义示例
public class MyTypeValue extends FractionatedValue {
public MyTypeValue(long value) {
super(
value,
new FractionSpecification(
FractionDefinition.builder()
.name("the minimal fraction unit")
.shortNotation("foo")
.minimalUnitsAmount(1)
.build(),
FractionDefinition.builder()
.name("another fraction unit")
.shortNotation("baz")
.minimalUnitsAmount(60)
.build(),
FractionDefinition.builder()
.name("the last fraction unit")
.shortNotation("foo baz")
.minimalUnitsAmount(3600)
.build()
)
);
}
}
...
assertEquals(
"2foo 46baz 40foo baz",
new MyTypeValue(10000).fullString()
);