Search code examples
javabigdecimal

BigDecimal with decimates value?


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

Solution

  • 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