We are working with financial calculations. I found this post about storing money values as decimals: decimal vs double! - Which one should I use and when?
So I'm storing amount as decimals.
I have the following calculation: 12.000 * (1/12) = 1.000
If I use a decimal data type for storing the amount and the result amount I not get the expected result
// First approach:
decimal ratio = 1m / 12m;
decimal amount = 12000;
decimal ratioAmount = amount * ratio;
ratioAmount = 999.9999999999999
// Second approach:
double ratio = 1d / 12d;
decimal amount = 12000;
decimal ratioAmount = (decimal)((double)amount * ratio);
ratioAmount = 1.000
// Third approach:
double ratio = 1d / 12d;
double amount = 12000;
double ratioAmount = amount * ratio;
ratioAmount = 1.000
What is the best way? Everyone is talking about that amounts/money must be stored as decimals.
No comments:
Post a Comment