I have
private static final BigDecimal ONE_HUNDRED = new BigDecimal(100);
private static final BigDecimal TEN = new BigDecimal(10);
BigDecimal decimal = new BigDecimal(1050);
I need to get 10% I write
BigDecimal decimalResult = decimal.divide(ONE_HUNDRED).multiply(TEN)//100, 10
But Intellij IDE says:
'BigDecimal.divide()' called without a rounding mode argument more...
I added BigDecimal.ROUND_HALF_UP
and all others but I get wrong result. I need 1050/100 = 10.5
but if I add BigDecimal.ROUND_HALF_UP
result = 11
.
How can I correctly divide with scale parameters?
divide(BigDecimal divisor) scale() – divisor. scale()). Parameters: This method accepts a parameter divisor by which this BigDecimal is to be divided for obtaining quotient. Return value: This method returns a BigDecimal which holds the result (this / divisor).
scale() is an inbuilt method in java that returns the scale of this BigDecimal. For zero or positive value, the scale is the number of digits to the right of the decimal point. For negative value, the unscaled value of the number is multiplied by ten to the power of the negation of the scale.
To divide two decimal numbers (or an integer by a decimal or vice-versa), you can use simple double division to ensure a decimal result. When working with larger numbers or numbers that needs to be extremely precise, you can use the BigDecimal Java class instead of floating point arithmetic.
public static double divide(double d1, double d2) {
BigDecimal b1 = new BigDecimal(d1);
BigDecimal b2 = new BigDecimal(d2);
return b1.divide(b2, 2, RoundingMode.DOWN).doubleValue();
}
This example returns 105.0000
public class TestBigDecimal {
static BigDecimal decimal = new BigDecimal(1050).setScale(4, BigDecimal.ROUND_HALF_UP);
static BigDecimal ONE_HUNDRED = new BigDecimal(100);
static BigDecimal TEN = new BigDecimal(10);
public static void main(String[] args)
{
BigDecimal decimalResult = decimal.divide(ONE_HUNDRED).multiply(TEN) ;
System.out.println(decimalResult);
}
}
You should adjust the scale during the creation of decimal
variable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With