tags:

views:

357

answers:

3

What is the best way to format a decimal if I only want decimal displayed if it is not an integer.

Eg:

decimal amount = 1000M
decimal vat = 12.50M

When formatted I want:

Amount: 1000 (not 1000.0000)
Vat: 12.5 (not 12.50)
+9  A: 
    decimal one = 1000M;
    decimal two = 12.5M;

    Console.WriteLine(one.ToString("0.##"));
    Console.WriteLine(two.ToString("0.##"));
Richard Nienaber
Its' important to remember you've gotta include as many # signs as you want to display decimal places if you use this method.
AlexCuse
+5  A: 

Try this:

decimal one = 1000M;    
decimal two = 12.5M;    
decimal three = 12.567M;    
Console.WriteLine(one.ToString("G29"));    
Console.WriteLine(two.ToString("G29"));
Console.WriteLine(three.ToString("G29"));

For a decimal value, the "G29" format specified is the same as "0.#############################".

Unlike "0.##" it will display all significant decimal places (a decimal value can not have more than 29 decimal places).

Joe
A: 

I am having problem displaying decimal using G29 for 0.00008 gets truncated to 8E-05

Unless I use this "0.#############################" then it displays the desired result

Which is kind of strange

Discussed on this http://blogs.msdn.com/bclteam/default.aspx?p=11

turash