18

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)
Thomas Jespersen
  • 11,493
  • 14
  • 47
  • 55

2 Answers2

34
    decimal one = 1000M;
    decimal two = 12.5M;

    Console.WriteLine(one.ToString("0.##"));
    Console.WriteLine(two.ToString("0.##"));
Richard Nienaber
  • 10,324
  • 6
  • 55
  • 66
  • 2
    Its' important to remember you've gotta include as many # signs as you want to display decimal places if you use this method. – AlexCuse Oct 19 '08 at 15:45
25

Updated following comment by user1676558

Try this:

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

For a decimal value, the default precision for the "G" format specifier is 29 digits, and fixed-point notation is always used when the precision is omitted, so this 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).

The "G29" format specifier is similar but can use scientific notation if more compact (see Standard numeric format strings).

Thus:

decimal d = 0.0000000000000000000012M;
Console.WriteLine(d.ToString("G"));  // Uses fixed-point notation
Console.WriteLine(d.ToString("G29"); // Uses scientific notation
Joe
  • 122,218
  • 32
  • 205
  • 338
  • 1
    G29 uses scientific notation in certain scenarios (refer to the [MSDN documentation](https://msdn.microsoft.com/en-us/library/dwhawy9k(v=vs.110).aspx#Anchor_5)), 0.############################# is like a G29 that doesn't revert to scientific notation. – user1676558 Feb 16 '17 at 00:33
  • 1
    Sure, and sorry to be a pest. G actually preserves trailing zeros unlike G29 and 0.#############################. G shows the decimal 'as is', so to speak. G29 removes trailing zeros but can also revert to scientific notation if it's more compact. 0.############################# does not revert to scientific notation but does remove trailing zeros. The decimal 0.000010m can demonstrate these differences. – user1676558 Feb 16 '17 at 17:07
  • `12.0M.ToString("G")` outputs `12.0` whereas `12.0M.ToString("G2")` outputs `12` – Myster Jul 13 '21 at 05:38