Reputation: 1717
I want to divide BigDecimals
, 1 / 14819.79865821543
, but the result is 0
instead of 0.00006748
where coinRateInUSDWalletTo = 14819.79865821543 and amount = 1
BigDecimal numberOfCoinsToTransfer = amount.divide(
new BigDecimal(coinRateInUSDWalletTo),
RoundingMode.HALF_UP);
Upvotes: 0
Views: 74
Reputation: 21104
You have to specify a scale
for the BigDecimal
.
final BigDecimal coinRateInUSDWalletTo = new BigDecimal("14819.79865821543");
final BigDecimal result = BigDecimal.ONE.divide(
coinRateInUSDWalletTo,
10 /* Scale */,
RoundingMode.HALF_UP
);
Note also the use of BigDecimal.ONE
. No need to create another one (lol).
Upvotes: 2
Reputation: 332
You forgot to give the scale.
Following is the declaration for BigDecimal.divide() method.
public BigDecimal divide(BigDecimal divisor, int scale, RoundingMode roundingMode)
If you specify scale 8 then you will get your desired answer: 0.00006748
BigDecimal numberOfCoinsToTransfer = amount.divide(new BigDecimal
(coinRateInUSDWalletTo),8, RoundingMode.HALF_UP);
Upvotes: 2