Polarbear0106 - 1 year ago 99
Java Question

# How can I shorten a BigInteger value?

I'm trying to shorten BigInteger values to shorter versions. I have to use BigInteger in order to handle the insanely huge numbers my game is meant to handle.

For example:

1000 to 1.000K

5821 to 5.821K

10500 to 10.500K

101800 to 101.800K

2000000 to 2.000M

7800000 to 7.800M

92150000 to 92.150M

123200000 to 123.200M

1 000 000 000 000 000 000 to 1.000E

1 000 000 000 000 000 000 000 to 1.000Z

1 000 000 000 000 000 000 000 000 to 1.000Y(otta)

611 781 555 431 000 000 000 000 000 to 611.781Y

I saw a method using long values, but for my purpose long cannot store big enough values so I have to use BigIntegers. How can I format it in such a way using BigInteger?
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. I am trying to make a Android clicker game and for that it needs to store values that are WAY bigger!

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
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download