Avatar ·

How to output decimal with two decimal places in C#?

Hello everyone! I'm a beginner C# developer and I've encountered a problem with formatting decimal numbers. I need to output a product price in format with two decimal places, for example: 12.50, 99.99, 145.00.

\n\n

The problem is that when I simply use Console.WriteLine or ToString(), I get a different number of digits. Here's my code:

\n\n
decimal price = 12.5m;\ndecimal tax = 0.12345m;\ndecimal total = 150m;\n\nConsole.WriteLine(price);   // Outputs: 12,5\nConsole.WriteLine(tax);     // Outputs: 0,12345\nConsole.WriteLine(total);   // Outputs: 150
\n\n

I tried different options, but they don't work as needed. For example, I wrote:

\n\n
Console.WriteLine(price.ToString("0.00")); // Outputs: 12,50 - this is fine\nConsole.WriteLine(total.ToStr