Reputation: 28228
I'm trying to format BigInteger numbers to a more humanly readable form
Examples:
1000 -> 1.000K
5821 -> 5.821K
10500 -> 10.500K
101800 -> 101.800K
2000000 -> 2.000M
7800000 -> 7.800M
92150000 -> 92.150M
123200000 -> 123.200M
1 000 000 000 000 000 000 -> 1.000E
1 000 000 000 000 000 000 000 -> 1.000Z
1 000 000 000 000 000 000 000 000 -> 1.000Y
611 781 555 431 000 000 000 000 000 -> 611.781Y
I saw a method using long values, but for my purpose long cannot store big enough values so I have to use BigInteger
s. How can I format it in such a way using BigInteger?
In my case, the max amount it is supposed to handle is:
1 000 000 000 000 000 000 000 000 000 and is formatted to 1.000B
EDIT
No, this is not a duplicate of this post. I have to use BigInteger for this to work and it has to be done using BigInteger. Long values(as the other post asks about) does not store big enough values compared to what i need
Upvotes: 1
Views: 596
Reputation: 6008
Divide the value until a value less then 1000 is retrieved.
Determine the suffix (K, M, etc.) by means of the number of times you divided.
Determine the decimals using the remainder of the last division.
For instance:
public String formatNumber(BigInteger value)
{
// Initialize suffixes
String[] suffixes = new String[]{null, 'k', 'M', ....};
// Initialize divider
BigInteger thousand;
thousand = new BigInteger(1000);
// Initialize divisions
BigInteger final_value;
BigInteger remainder;
int nr_divisions;
final_value = value;
remainder = null;
nr_divisions = 0;
// Divide until final value less then 1000
BigInteger[] division;
while (final_value.compareTo(thousand) >= 0)
{
division = final_value.divideAndRemainder(thousand);
final_value = division[0];
remainder = division[1];
nr_divisions++;
}
// Maybe no divisions
if (nr_divisions == 0)
return (value.toString());
// Determine suffix
// Some check required since number of divisions may exceed the number of suffixes provided
String suffix;
suffix = suffixes[nr_divisions];
// Compose string
return (final_value.toString() + "." + String.format("%03d", remainder.intValue()) + suffix);
} // formatNumber
Upvotes: 3
Reputation: 1596
From BigInteger to string: How to convert locale formatted number to BigInteger in Java?
After that you need something like this (needs improvements):
public static void main(String[] args) throws Exception {
print("1.034");
print("21.034.234");
print("1.034.234.321");
}
private static String convert(String points) {
String[] letters = new String[]{"k", "M", "G"};
int size = points.length();
String after = points;
if (size > 3) {
int firstPoint = points.indexOf(".");
after = points.substring(0, firstPoint + 4);
int x = (size - firstPoint - 3)/4;
after += letters[x];
}
return after;
}
static void print(String x) {
System.out.println(x + " is " + convert(x));
}
It's really not that hard to write piece of code (like less than 20 lines)
Upvotes: 2