Search code examples
javabigdecimal

How to divide with BigDecimals


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);

Solution

  • 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).