How do I format to only include decimal if there are any

前端 未结 2 2060
长发绾君心
长发绾君心 2021-02-19 09:47

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


        
相关标签:
2条回答
  • 2021-02-19 10:29
        decimal one = 1000M;
        decimal two = 12.5M;
    
        Console.WriteLine(one.ToString("0.##"));
        Console.WriteLine(two.ToString("0.##"));
    
    0 讨论(0)
  • 2021-02-19 10:36

    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
    
    0 讨论(0)
提交回复
热议问题