Convert from String to BigDecimal to calculate math in currency

I am working on a project that requires simple math, but it comes in the form of a string. I am new to Java / Android, so I'm looking for help converting from String to a data type suitable for this operation. At first I thought Float was right, but after reading elsewhere and introducing myself to the class of numbers, it seems like BigDecimal is correct. Am I on the right track? For now, I just want to deduct the amount of payments from the original invoice amount. I feel that this code is simple but clumsy, and I suspect that I am missing a lot about the nuances of working with currency. How would you do that? All tips are welcome!

// capture variables from sending activity String invoiceAmt = getIntent().getStringExtra("invoiceAmt"); String paymentsSum = getIntent().getStringExtra("paymentsSum"); // convert strings to BigD 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()); 
+4
source share
1 answer

BigDecimal is a great approach. Therefore, int or long used to store cents. I heard some people like Joda-Money , but I never used it myself.

See this question .

In the code you posted, make sure that the String you receive does not have currency characters in them.

+5
source

Source: https://habr.com/ru/post/1339402/


All Articles