0
double depositAmount = Double.parseDouble(etDepositAmount.getText().toString());
                    BigDecimal depositAmountSafe = BigDecimal.valueOf(depositAmount);
                    BigDecimal userBalance = BigDecimal.valueOf(user.getBalance());

                    int comparisonResult = depositAmountSafe.compareTo(userBalance);

                    if (comparisonResult > 0) {
                        Toast.makeText(contex, R.string.INSUFFICIENT_BALANCE, Toast.LENGTH_SHORT).show();
                        return;
                    }
                    Deposit deposit = createDeposit();

In the above piece of code, I should be able to create a deposit if only the entered sum for the amount is less or equal to the user's balance. But for example if the user's balance is 62921.0, I am able to enter 62921.0000000000000001 and get the deposit created. How do I set the number of decimals? And if not, how can I enforce that the user can only enter a maximum number of digits as decimals. For example a maximum of 3 digits to the right of a a decimal point(eg. x.123 and not x.1234) for an EditText.

bko00
  • 39
  • 7
  • 3
    Your first two lines are a mistake. Once you convert the `String` to a `double` you've lost precision. `BigDecimal depositAmountSafe = new BigDecimal(etDepositAmount.getText().toString());` – Elliott Frisch Jul 06 '23 at 00:02

1 Answers1

1

You should be using the BigDecimal constructor, instead of the valueOf method.

Additionally, you should be parsing the amount directly from the String value, as opposed to using a Double#parseDouble call.  It will preserve the precision.

BigDecimal depositAmountSafe = new BigDecimal(etDepositAmount.getText().toString());
BigDecimal userBalance = new BigDecimal(user.getBalance());

int comparisonResult = depositAmountSafe.compareTo(userBalance);

if (comparisonResult > 0) {
    Toast.makeText(contex, R.string.INSUFFICIENT_BALANCE, Toast.LENGTH_SHORT).show();
    return;
}
Deposit deposit = createDeposit();

This will cause your if-conditional check of comparisonResult to match.

Consider the following example.

BigDecimal depositAmountSafe = new BigDecimal("62921.0000000000000001");
BigDecimal userBalance = new BigDecimal("62921.0");

int comparisonResult = depositAmountSafe.compareTo(userBalance);

if (comparisonResult > 0) {
    System.out.println("insufficient balance");
    return;
}
System.out.println("create deposit");

Output

insufficient balance

In regard to setting the decimal places, here is a relevant question and answer.
StackOverflow – Limit Decimal Places in Android EditText.

Reilas
  • 3,297
  • 2
  • 4
  • 17