C# display decimal without trailing zeros

C# display decimal without trailing zeros!
How to display decimals in C# without trailing zeros? Well, there are a couple of options. First of all, how many decimals do you want to show? Do you want to show 0, 1, 2, etc. Well the easy way to do it is just like this!

var decimalList = new List<decimal> { 10, 20.00m, 30.5m, 40.5000m, 50.125m, 60.12500m, 70.123456789123m, 0.000m };
foreach (var decimalValue in decimalList)
{
    Console.WriteLine(decimalValue.ToString("0.##########"));
}

// Output
// 10
// 20
// 30,5
// 40,5
// 50,125
// 60,125
// 70,123456789
// 0

Console.WriteLine(123.321m.ToString("0"));
// Output
// 0

In the code example above, the hashtags (#) means how many decimal places the number will round to. So simply said, if you need 2 decimals, use 2 hashtags, if you want 0 decimals, use “0.” or just simply “0”

C# display decimal without trailing zeros
C# display decimal without trailing zeros


Checkout these simple easy to read articles about add object to Listreverse for loops an foreach loops f you want som extra reading:
https://www.jennerstrand.se/add-object-to-list-in-c-sharp.
https://www.jennerstrand.se/reverse-for-loop-in-c-sharp.
https://www.jennerstrand.se/foreach-loop-in-c-sharp-simple-use.

For loop in C# – Simple how to use and the links above is part of a series of easy read, quick use examples you can use in your c#/.net coding!

Leave a Reply

Your email address will not be published. Required fields are marked *

Please reload

Please Wait