-1

I have to perform operation on Money(basically dollars). I have to get the price of a product then multiply with the Quantity and in a same way do the transactions.

Currently i am using the double and at some places float to perform operations on amount. They give me output like 13.789689 but i need only up to 2 digits. So that i have applied

String value = String.format(Locale.ENGLISH, "%.2f", 13.789689);

to get that upto 2 digits. But now the problem is results are not coming accurate. Also i am to saving the Transactions information into the database and that shows variations in Cash and CC trans. I am So frustrated by this because it's operation with money and i am loosing that. Please guide me what to best in that case.

Helping_Hand
  • 213
  • 1
  • 5
  • 10

3 Answers3

3

Don't use float or double for anything money related, if you need exact results (and you probably do). Try BigDecimal instead.

Gabriel Negut
  • 13,860
  • 4
  • 38
  • 45
  • `BigDecimal` will probably work, but it's quite expensive to deal with. `Long` is usually plenty. – chrylis -cautiouslyoptimistic- Aug 30 '13 at 07:56
  • `BigDecimal` is not exact when you convert dollars to euros or when you compute the monthly interest for an annual percentage rate or need any calculation other than simple addition, subtraction, and multiplication. – Eric Postpischil Aug 30 '13 at 11:36
  • @EricPostpischil Long is not exact for those operations either. BigDecimal arithmetic does have what is needed in practice, means to enforce the appropriate rounding rule for each inexact calculation. Long only supports truncation, which is rarely appropriate. – Patricia Shanahan Aug 30 '13 at 14:03
  • @PatriciaShanahan: My comment does not address the merits of `long` versus `BigDouble`. It addresses a fault in this answer. This answer suggests that `BigDecimal` should be used if exact results are needed. That is misleading and should be corrected. – Eric Postpischil Aug 30 '13 at 14:10
3

There is nothing specific to android. In Java, it is recommended that all the monetary calculations are to be carried out by BigDecimal data type so that there will not be any rounding off issues that you would face in float and double

Here are the few links that might help you 1,2,3.

Community
  • 1
  • 1
codeMan
  • 5,730
  • 3
  • 27
  • 51
0

You can use DecimalFormat for this , i.e.

    Double d=13.789689
    DecimalFormat deciFor= new DecimalFormat("##.##");
    String value=deciFor.format(d);

Result value will be 13.79

Mukesh Kumar Singh
  • 4,512
  • 2
  • 22
  • 30