Avatar ·

Decimal vs Double in C#: which data type to choose and when to use?

Hi everyone! I'm a beginner in C# and while writing a calculator for an online store, I encountered a problem choosing the data type for monetary calculations.\n\nI have a simple code:\n\n```csharp\ndouble price = 19.99;\ndouble tax = 0.21;\ndouble total = price * (1 + tax);\nConsole.WriteLine(total); // Outputs something like 24.1879... instead of 24.1879\n```\n\nI expected to get exactly 24.1879, but sometimes strange tails like 24.187899999999997 appear. This doesn't happen all the time, but often enough to break price comparison logic.\n\nI googled and found that there is a `decimal` type, but I don't understand the difference. Both seem to store fractional numbers. When I replaced `double` with `decimal`:\n\n```csharp\ndecimal price = 19.99m;\ndecimal tax = 0.21m;\ndecimal total = price * (1 + tax);\nConsole.WriteLine(total); // 24.1879