Percentage calculation for values ββless than 1 and greater than 0
I am trying to display a percentage using BigDecimal.
for example if i need to do
double val = (9522 / total ) * 100;
System.out.println("Val is :" + val);
where the total is 1200000.
I want to display the calculation as a percentage, but since the calculation comes to a value less than 0, I cannot display the percentage
I have also tried
BigDecimal decimal = new BigDecimal((9522 * 100 ) / total);
BigDecimal roundValue = decimal.setScale(2, BigDecimal.ROUND_HALF_UP);
System.out.println("decimal: " + decimal);
System.out.println("roundValue: " + roundValue);
but with the same result.
How do I display the percentage even if it is in decimal format?
source to share
BigDecimal decimal = new BigDecimal ((9522 * 100) / total);
This is not how you perform operations with BigDecimal
: by the time of creation, the BigDecimal
precision has disappeared because the calculation (9522 * 100 ) / total
is done at compile time. This is why the result is the same as with integers: in fact, the whole calculation is done in integers.
This is how you compute objects BigDecimal
:
BigDecimal decimal = new BigDecimal(9522)
.multiply(new BigDecimal(100))
.divide(new BigDecimal(total));
source to share
You may be missing a role.
double val = (9522 / (double)total ) * 100;
System.out.println("Val is :" + val);
My suspect is that total is an int, and therefore 9522/1200000 results in an integer which is truncated to 0 because the operation implies that the result must be less than 1. If you convert total to double the result will be double, and you can keep the decimal places.
source to share