Search code examples
c#stringdoubledecimal

How to remove trailing zeros when using doubles in strings with C#?


I have some doubles and I need to print them (in reality I use them in WPF UI) but the resulting string has too many characters (or digits) and I need to show all the significant ones. Removing trailing zeros would help:

"1.00000000" => "1", "2.50000000" => "2.5", "205.01280000" => "205.0128"

I know I can round() the numbers to a given number of digits but it decreases precision... Is there a function or any way to remove trailing zeros?

Edit: my english was terrible at the time I asked this question. I didn't know the word "trailing" was a thing and so didn't know there was already a question about this here.

Thanks to all the people who took the time to answer anyway!


Solution

  • string source = "2.4200";
    string output = double.Parse(source).ToString();
    

    Credits: here