简体   繁体   中英

Percentage Calculation for values less than 1 and greater than 0

I am trying to display the percentage using BigDecimal.

for example if i have to do

    double val = (9522 / total ) * 100;

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

where total is 1200000.

I want to display the calculation as a percentage but since the calculation comes to a value less than 0 , I am unable to display the percentage

I 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 can I display the percentage even if it is in Decimals?

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 a double will cause Java to perform the correct type of division instead of defaulting to integer division.

You have to inform Java that you want at least one of the numerator or denominator treated as a double, to make sure the result is a double.

This will work:

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

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

BigDecimal decimal = new BigDecimal((9522 * 100 ) / total);

This is not how you do operations on BigDecimal : by the time the BigDecimal is constructed, the precision is gone, because the calculation (9522 * 100 ) / total is done at compile time. That's why the result is the same as with integers: in fact, the entire calculation is done in integers.

Here is how you calculate with BigDecimal objects:

BigDecimal decimal = new BigDecimal(9522)
    .multiply(new BigDecimal(100))
    .divide(new BigDecimal(total));

If you divide two integer you will get the result truncated. Add a .0 so that it is converted to floating point, and then you will not get a truncated result

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

You may be missing a cast.

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

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

My suspect is that total is an int, and hence 9522/1200000 results in an integer, which is truncated to 0 because the operation implies that the result must be smaller than 1. If you convert total to double the result is going to be a double, and you will be able to retain the decimals.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM