Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How accurate is BigDecimal.doubleValue() if no operation is applied on the amount

I NEED to be sending a value as 'double', however I am:

  1. Taking a value as a long
  2. Converting it to BigDecimal
  3. Calling method scaleByPowerOfTen on the BigDecimal (using '-2' to make cents a whole amount value).
  4. Calling doubleValue() on the BigDecimal to get the needed value as double.

Now I know that double values lose precision when you apply arithmetic operations on them, however what could I possibly get if I try to send a double value as-is based on BigDecimal, such as (I believe) the above scenario is.

This is important as I have to be sending money values over SOAP in this manner - no other way.

I also have the scenario where the BigDecimal is created using as a String, then doubleValue() is called on it. What could I get in this case ?

EDIT: Sample code for this:

long amountInCents = 1852;
BigDecimal amountInWholeUnits = BigDecimal.valueOf(amountInCents).scaleByPowerOfTen(-2);
double amountToSend = amountInWholeUnits.doubleValue();

As for the case where the amount is provided as String:

double amountToSend = new BigDecimal("18.52").doubleValue();

UPDATE

Now that I have sample code, I just thought I can test and see, so I did a for loop and used System.out.println: so far so good, the values are correct, so I believe this will be the same when sent through SOAP. Please correct me if I'm wrong.

like image 762
abdelrahman-sinno Avatar asked Nov 09 '22 09:11

abdelrahman-sinno


1 Answers

Since one cent is equal to 1/100 of a dollar, and since the number 1/100 or 0.01 cannot be represented exactly as a binary floating-point number, some slight loss of accuracy will occur. In your particular example of $18.52, the resulting double will hold the closest double value to 18.52, but it will not be exactly equal to 18.52.

like image 181
Sam Estep Avatar answered Nov 14 '22 21:11

Sam Estep