Double VS Decimal In C#



If you are using double or float in financial arithmetic operations, please stop ⛔ this !!

the basic difference between double and decimal is that decimal and float is a numeric type with base 2
that means only number with base 2 are expressible in these types
while in our daily basis we use numbers with base 10, 0-9 numbers


Sample code:

decimal dcm = 4m / 12m; // 0.3333333333333333333333333333
double dbl = 4.0 / 12.0;// 0.333333333333333
dcm + dcm + dcm + dcm + dcm + dcm; //1.9999999999999999999999999998 
dbl + dbl + dbl + dbl + dbl + dbl; //2

As you can see in the upper code there's a rounding error, 
the correct value should be 1.9  while in double it was 2

References:

Comments

Popular posts from this blog

Sitecore Multi list Code Data Source

Organize media files using Sitecore PowerShell

C# Numeric types Overflow