Don't use float or double for any calculations that require an exact answer.
The float and double types are certainly ill-suited for monetary calculations
Because it is impossible to represent 0.1 (or any other negative power of ten) as a float or double exactly.
Use bigdecimal, Int or long for monetary calculations.
Use bigdecimal if you want the system to keep track of the decimal point and you don't mind the inconvenience of not using a primitive type.
If performance is of the essence, if you don't mind keeping track of the decimal point yourself, and if the quantities aren't too big, use Int or long.
If the quantities don't exceed nine decimal digits, you can use Int.
If they don't exceed eighteen digits, you can use long.
If the quantities exceed eighteen digits, you must use bigdecimal.
Here is an example:
Import java. Math. bigdecimal;
Public class test1 {
Public static void main (string ARGs []) {
System. Out. println ("method test1 () executed! ");
Test1 ();
System. Out. println ("method Test2 () executed! ");
Test2 ();
System. Out. println ("method test3 () executed! ");
Test3 ();
}
Public static void test1 (){
DoubleFunds = 1.00;
Int itemsbought = 0;
For (DoublePrice =. 10; Funds> = price; Price + =. 10 ){
Funds-= price;
Itemsbought ++;
}
System. Out. println (itemsbought + "itmes bought .");
System. Out. println ("Change: $" + funds );
}
Public static void Test2 (){
FinalBigdecimalTen_cents = new bigdecimal (". 10 ");
Int itemsbought = 0;
BigdecimalFunds = new bigdecimal ("1.00 ");
For (BigdecimalPrice = ten_cents; funds. compareto (price)> = 0; Price = Price. Add (ten_cents )){
Itemsbought ++;
Funds = funds. Subtract (price );
}
System. Out. println (itemsbought + "itmes bought .");
System. Out. println ("Change: $" + funds );
}
Public static void test3 (){
Int itemsbought = 0;
IntFunds = 100;
For (IntPrice = 10; Funds> = price; Price + = 10 ){
Itemsbought ++;
Funds-= price;
}
System. Out. println (itemsbought + "items bought .");
System. Out. println ("money left over:" + funds + "cents ");
}
}
Result:
MethodTest1 ()Executed!
3Itmes bought.
Change:$0.3999999999999999
MethodTest2 ()Executed!
4Itmes bought.
Change:$0.00
MethodTest3 ()Executed!
4Items bought.
Money left over:0 cents
Comment:
The result of test1 () is the wrong answer!