你好我是新來的java任何人都可以幫助我嗎?如何將2k,1m,1g等轉換爲2000,1000000等
該代碼轉換 2000至2k和百萬1米等
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 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
Map.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;
}
我需要其中反向例如 2K到2000和1M轉化爲百萬
把'k'替換爲'000'?如in,'string.replace(「k」,「000」)'? –
好的感謝幫助。 – Prateek218
未提及,但有效值也可以是'2k7'。 – arminb