Lluis Martinez
Lluis Martinez

Reputation: 1973

Compute percentage for bigdecimals

I haven't found any native method to do this, so I created my own in a helper class:

public static BigDecimal percentage(BigDecimal base, BigDecimal pct){
    return base.multiply(pct).divide(new BigDecimal(100));
}

But I don't quite like it, I wonder if the API has something similar. The Number class (ancestor of BigDecimal) would be a nice place.

Upvotes: 35

Views: 79972

Answers (5)

Hooman
Hooman

Reputation: 134

You can also use UNNECESSARY rounding mode and scale of 2, if your number is an integer.

It would be like this:

// rate == 0.10
BigDecimal rate = BigDecimal.TEN
        .divide(BigDecimal.valueOf(100), 2, RoundingMode.UNNECESSARY);

This way you can also avoid facing warnings like:

BigDecimal.divide()' called without a rounding mode argument

without needing to suppress them.

Upvotes: 1

trashgod
trashgod

Reputation: 205865

See also DecimalFormat. You can use the parent's factory method NumberFormat.getPercentInstance() as shown here, here, et al.

Upvotes: 5

user85421
user85421

Reputation: 29700

I don't think there is an API for that (I never needed it).
Your solution seams good to me, maybe you just add the constant ONE_HUNDRED:

public static final BigDecimal ONE_HUNDRED = new BigDecimal(100);

public static BigDecimal percentage(BigDecimal base, BigDecimal pct){
    return base.multiply(pct).divide(ONE_HUNDRED);
}

probably not that much gain, only if called very often

eventually put it in some Util class...

Upvotes: 34

Valentyn Danylchuk
Valentyn Danylchuk

Reputation: 467

You may want to implement the division by 100 using BigDecimal.scaleByPowerOfTen(-2).

It adds up if you do it a million times. It is much faster in my experience.

There is also a similar method BigDecimal.movePointLeft(2) - see the other thread for details and decide which one works better for you.

Upvotes: 15

Michael Borgwardt
Michael Borgwardt

Reputation: 346397

Feel free to subclass BigDecimal and add that method. Beyond that, what do you expect? You know where to find the API and confirm that the class you would like to have that method doesn't. Personally, I'd say the functionality is so trivial that there wouldn't be much of a point in having it in the standard API.

Upvotes: 7

Related Questions