开发者

Converting from String to BigDecimal to do math on currency

开发者 https://www.devze.com 2023-02-10 04:44 出处:网络
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

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 Strings you are receiving don't have currency symbols in them.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号