C
C
Che_Bu_Rashka2018-04-18 16:47:59
Java
Che_Bu_Rashka, 2018-04-18 16:47:59

Working with BigDecimal, how to discard the fractional part?

I need to calculate A * B / 100

BigDecimal result = null;
        BigDecimal a = new BigDecimal(this.getA());
        a.setScale(2, RoundingMode.UP);

        BigDecimal b = new BigDecimal(this.getB());
        b.setScale(2, RoundingMode.UP);

        result = a.multiply(b).divide(new BigDecimal(100), RoundingMode.UP);
        result.setScale(0, RoundingMode.UP);
        if (result != null) {
           System.out.println (result.toString());
        }

The result is 15.874574. And you need 15, that is, discard the fractional part. As I understood setScale(0, RoundingMode.UP) should help, but no... By the way, in A there are 2 decimal places, and in B - 4. Here he gave the result with the 6th
How is it done? Thank you.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
R
Ruslan Lopatin, 2018-04-18
@Che_Bu_Rashka

setScale() returns a new BigDecimal instance. And you ignore him.
result = result.setScale(0, RoundingMode.UP);

S
Sergey Gornostaev, 2018-04-18
@sergey-gornostaev

BigDecimal a = BigDecimal("15");
BigDecimal b = BigDecimal("2");
BigInteger c = a.divide(b).toBigInteger();

C
Cr2ed, 2018-04-18
@Cr2ed

poke

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question