Friday, March 9, 2018

c# - Financial calculations: double or decimal?

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

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...