diff options
| author | ilotterytea <iltsu@alright.party> | 2022-10-06 01:09:24 +0600 |
|---|---|---|
| committer | ilotterytea <iltsu@alright.party> | 2022-10-06 01:09:24 +0600 |
| commit | 504825282ff0e781891621672028e706c2655773 (patch) | |
| tree | d4fb24d76896dcebc287bfc9bb98c6a3063f1253 | |
| parent | bb4d02f9b7d4018b2fbf508cd882a57b54565d95 (diff) | |
number formatter (thx to guy from stackoverflow)
| -rw-r--r-- | core/src/com/ilotterytea/maxoning/utils/formatters/NumberFormatter.java | 32 |
1 files changed, 32 insertions, 0 deletions
diff --git a/core/src/com/ilotterytea/maxoning/utils/formatters/NumberFormatter.java b/core/src/com/ilotterytea/maxoning/utils/formatters/NumberFormatter.java new file mode 100644 index 0000000..96c0258 --- /dev/null +++ b/core/src/com/ilotterytea/maxoning/utils/formatters/NumberFormatter.java @@ -0,0 +1,32 @@ +package com.ilotterytea.maxoning.utils.formatters; + +import java.util.Map; +import java.util.NavigableMap; +import java.util.TreeMap; + +public class NumberFormatter { + 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 + + 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; + } +} |
