Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compute percentage for bigdecimals

Tags:

java

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.

like image 789
Lluis Martinez Avatar asked Jan 21 '10 14:01

Lluis Martinez


People also ask

How do you get a percentage in Java?

Percentage = (Obtained score x 100) / Total Score To get these parameters (inputs) from the user, try using the Scanner function in Java.

How do you convert a double to a percent 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.

What is rounding mode in Bigdecimals Java?

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.


2 Answers

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...

like image 167
user85421 Avatar answered Sep 29 '22 00:09

user85421


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.

like image 43
Valentyn Danylchuk Avatar answered Sep 29 '22 00:09

Valentyn Danylchuk