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?

+3


source to share


5 answers


The problem is you are doing integer division.

If you want fractional results, you need to do floating point division.



double val = (9522 / (double) total) * 100;

      

Casting one of your operands to double will cause Java to do the correct type of division, not integer division.

+8


source


You need to tell Java that you want at least one of the numerators or denominators to be treated as double, to ensure that the result is double.

This will work:



double val = ((double)9522 / total ) * 100;

System.out.println("Val is :" + val);

      

+3


source


If you split two integers, you get the truncated result. Add .0

so that it is converted to float and then you don't get the truncated result

new BigDecimal((9522.0 / total) *100);

      

+2


source


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));

      

+2


source


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.

+1


source







All Articles