I am working on a project that requires some simple math to be performed on currency, however it arrives in the form of a String. I am new to Java/Android so I am looking for help in converting from a String to a data type appropriate to this operation. At first I thought Float was right but after reading elsewhere and introducing myself to the numbers class, it appears BigDecimal is correct. Am I on the right track? At this point I simply want to subtract the sum of payments from an initial invoice amount. I get the feeling this code is simple but clumsy and I suspect I am missing a great deal about the nuances of working with currency. How would you do it? All advice warmly appreciated!
// capture variables from sending activity
String invoiceAmt = getIntent().getStringExtra("invoiceAmt");
String paymentsSum = getIntent().getStringExtra("paymentsSum");
// convert strings to BigD's
BigDecimal amt = new BigDecimal(invoiceAmt);
BigDecimal sum = new BigDecimal(paymentsSum);
// Do the math
BigDecimal invDue = amt.subtract(sum);
// insert the value (back to string) into textView
TextView tvInvoiceDue = (TextView)findViewById(R.id.InvoiceDue);
tvInvoiceDue.setText(invDue.toString());
BigDecimal
is a fine approach. So is using an int
or a long
to store cents. I've heard some people like Joda-Money but I've never used it myself.
See this question.
In the code you posted, make sure the String
s you are receiving don't have currency symbols in them.