3
\$\begingroup\$

I'm teaching myself BigDecimal and would appreciate a critique. In the code fragment below, I calculate a tip from user input: check and tip percentage (entered as integer):

 txt_check = txtcheck.getText().toString();
 tpercent = txttippct.getText().toString();

 BigDecimal hundred = new BigDecimal("100");
 BigDecimal pct = new BigDecimal(tpercent);

 BigDecimal bdpercent = pct.divide(hundred, 2,BigDecimal.ROUND_UNNECESSARY); 
 BigDecimal bdcheck = new BigDecimal(txt_check);
 BigDecimal bdtip = new BigDecimal(txt_check);
 bdtip = bdtip.multiply(bdpercent);
 BigDecimal bdtotal = new BigDecimal(txt_check);
 bdtotal = bdtotal.add(bdtip);

The code above appears to function correctly. To display these values I convert to string:

 scheck = new DecimalFormat("####.00").format(bdcheck.doubleValue());
 scheck = StringUtils.leftPad(scheck,7," "); 

Thanks for any input.

\$\endgroup\$
1
\$\begingroup\$

For such a simple calculation, the logic used for the bdtip and bdtotal variables wasnt straight forward. Instead of creating it with the value of one of the operands, then multiplying/adding it by the other operand, why not do something like the following:

txt_check = txtcheck.getText().toString();
tpercent = txttippct.getText().toString();

BigDecimal hundred = new BigDecimal("100");
BigDecimal pct = new BigDecimal(tpercent);

BigDecimal bdpercent = pct.divide(hundred, 2, BigDecimal.ROUND_UNNECESSARY); 
BigDecimal bdcheck = new BigDecimal(txt_check);

BigDecimal bdtip = bdcheck.mulitply(bdpercent);
BigDecimal bdtotal = bdcheck.add(bdtip);
\$\endgroup\$
1
\$\begingroup\$
  1. Following naming conventions makes the code easier to read. See Effective Java, 2nd Edition, Item 56: Adhere to generally accepted naming conventions

  2. new BigDecimal("100") could be a constant.

  3. DecimalFormat.format(Object number, StringBuffer toAppendTo, FieldPosition pos) accepts BigDecimal objects (without the necessity of converting it to double and loss of precision).

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.