Never use double or BigDecimal for currency; both are ridiculous.
You should always identify the appropriate fraction of the currency to be the unit and use a long to represent that.
For example,
if you are working with USD,
then a penny (1/100 of a USD) may be good.
If you are converting between currencies,
then 1/10_000 of the base currency (for example, USD) may be reasonable.
In the case of 1/10_000 of the base currency,
in my example 10_000 would be the value to store for $1 (one USD).
for Yen to USD you might want to use 1/10_000_000 USD as the 1 value (i.e. store 10_000_000 for $1).
Once you have a reasonable representation,
do integer math for currency (a long holds integer values).
Run this to see why double and BigDecimal are bad.
import java.math.BigDecimal;
import org.junit.Test;
public class GoofballsUseDouble
{
public void bigdecimalTest1()
{
final BigDecimal m1 = new BigDecimal(
0.1d);
final BigDecimal m2 = new BigDecimal(
0.2d);
final BigDecimal sum;
sum = m1.add(m2);
System.out.println("");
System.out.println("bigdecimalTest1");
System.out.println(" v1.a (0.1bd): " + m1);
System.out.println(" v2.a (0.2bd): " + m2);
System.out.println("sum.a (?): " + sum);
}
public void bigdecimalTest2()
{
final BigDecimal m1 = new BigDecimal(
"0.1");
final BigDecimal m2 = new BigDecimal(
"0.2");
final BigDecimal sum;
sum = m1.add(m2);
System.out.println("");
System.out.println("bigdecimalTest2");
System.out.println(" v1.a (0.1bds): " + m1);
System.out.println(" v2.a (0.2bds): " + m2);
System.out.println("sum.a (?): " + sum);
}
public void doubleTest()
{
final double m1 = 0.1d;
final double m2 = 0.2d;
final double sumM;
sumM = m1 + m2;
System.out.println("");
System.out.println("doubleTest");
System.out.println(" v1.a (0.1d): " + m1);
System.out.println(" v2.a (0.2d): " + m2);
System.out.println("sum.a (?): " + sumM);
System.out.printf(" v1.b (0.1d): %f%n",
m1);
System.out.printf(" v2.b (0.2d): %f%n",
m2);
if (.3d == sumM)
{
System.out.println("it r equalz");
}
else
{
System.out.println("double is not exact, of course");
}
}
@Test
public void theTest()
{
doubleTest();
bigdecimalTest1();
bigdecimalTest2();
}
}