Decimal, Float or Double data type always lose precision when multiplied, added or divided.
Regardless of programming languageRegardless of programming language we use, this behavior is universal. I would like you to go through following post if you want to understand in detail.
What Every Computer Scientist Should Know About Floating-Point Arithmetic
Otherwise, this is easy one, however addition doesn't apply to Salesforce because we have bigger precision data type - Floating point guide
Decimal v/s Double
Double
are typically 64 bit number but Decimal is 128 bit. With both types we can have unexpected results based on at which size the result is finished.
Take following example:-
Decimal total = 8.0/3.0; // 2.66666666666666666666666666666667
Decimal total2 = total*3.0; // 8.000000000000000000000000000000010
Double totald = 8.0/3.0; // 2.6666666666666665
Double totald2 = totald*3.0; // 7.999999999999999
System.debug(' ===>'+ (total));
System.debug(' ===>'+ (total2));
System.debug(' ===>'+ (totald));
System.debug(' ===>'+ (totald2));
In above example Decimal
had the greater memory than Double
so, ended up in more detailed result. FurtherThis further result into some unexpected result.