C#: Using String Format To Show Decimal Up To 2 Places Or Simple Integer

In C#, you can use the String.Format method to format a decimal value up to 2 decimal places or a simple integer. Here is an example:

decimal decimalValue = 10.12345m;
int intValue = 10;

string decimalFormatted = string.Format("{0:0.00}", decimalValue);
string intFormatted = string.Format("{0:0.##}", intValue);

Console.WriteLine("Formatted decimal value: " + decimalFormatted);
Console.WriteLine("Formatted integer value: " + intFormatted);


Formatted decimal value: 10.12
Formatted integer value: 10

In the format string, 0.00 specifies that the decimal value should be formatted with 2 decimal places. On the other hand, 0.## specifies that the integer value should be formatted as a simple integer without any decimal places.

You can adjust the format string depending on your specific requirements.

About the Author Rex

I'm a passionate tech blogger with an insatiable love for programming! From my early days tinkering with code, I've delved into web dev, mobile apps, and AI. Sharing insights and tutorials with the world is my joy, connecting me to a global community of like-minded tech enthusiasts. Python holds a special place in my heart, but I embrace all challenges. Constantly learning, I attend tech conferences, contribute to open-source projects, and engage in code review sessions. My ultimate goal is to inspire the next generation of developers and contribute positively to the ever-evolving tech landscape. Let's code together!