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.
Percentage = (Obtained score x 100) / Total Score To get these parameters (inputs) from the user, try using the Scanner function in Java.
Formatting Percentages The following code sample shows how to format a percentage. Double percent = new Double(0.75); NumberFormat percentFormatter; String percentOut; percentFormatter = NumberFormat.
The enum RoundingMode provides eight rounding modes: CEILING – rounds towards positive infinity. FLOOR – rounds towards negative infinity. UP – rounds away from zero. DOWN – rounds towards zero.
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...
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With