-1

I'm trying divide a value using BigDecimal, when this value is a decimates BigDecimal round this value and I wont to do that. I need the decimates value are shown. For example, if I do divide 10 / 3 = 3.33333, I need shown 3.33 but does show 3.00

How could I do this ?

//Result-> 10 / 2 = 3,3333333

BigDecimal result = new BigDecimal(0);
BigDecimal v1 = new BigDecimal(10);
BigDecimal v2 = new BigDecimal(3);
result = v1.divide(v2, BigDecimal.ROUND_UP);

//output = 3
//I need output = 3.33
FernandoPaiva
  • 4,410
  • 13
  • 59
  • 118

3 Answers3

2

The scale of BigDecimals that were initialized with ints is 0, meaning that rounding operations round to unity. With your example, the division rounds up to 4.

Set the scale of the first BigDecimal to 2, which be retained through the division. Also set the rounding mode to "down".

BigDecimal v1 = new BigDecimal(10).setScale(2);
BigDecimal v2 = new BigDecimal(3);
result = v1.divide(v2, BigDecimal.ROUND_DOWN);

Printing results now yields an output of 3.33.

You could have also used the RoundingMode enum as a drop-in replacement for the rounding constants. Additionally, you could have used ROUND_HALF_DOWN, ROUND_HALF_UP, or ROUND_HALF_EVEN (or their RoundingMode equivalents).

You could use a string with the appropriate number of decimal digits to set the scale implicitly.

BigDecimal v1 = new BigDecimal("10.00");  // scale of 2
rgettman
  • 176,041
  • 30
  • 275
  • 357
1

try to compile and run this java class, it works as you wish:

import java.math.*;
class decimal {
    public static void main(String[] args) {
BigDecimal result = new BigDecimal(0);
BigDecimal v1 = new BigDecimal(10);
BigDecimal v2 = new BigDecimal(3);
result = v1.divide(v2,2,BigDecimal.ROUND_HALF_UP);
System.out.println(result);
}
}

output : 3.33

you want two decimal digits this is why I set scale=2

adrCoder
  • 3,145
  • 4
  • 31
  • 56
1

Try to add scale to BigDecimal, like this:

public class User {

    public static void main(String[] args) {

        BigDecimal result = new BigDecimal(0);
        BigDecimal v1 = new BigDecimal(10).setScale(2);
        BigDecimal v2 = new BigDecimal(3);
        result = v1.divide(v2, BigDecimal.ROUND_DOWN);

        System.out.println(result);

    }
}
Laszlo Lugosi
  • 3,669
  • 1
  • 21
  • 17