C# Decimal Formatting Query

后端 未结 4 1559
醉话见心
醉话见心 2021-01-15 04:49

I am trying to format a decimal so that it will get displayed as so:

14.5 should get displayed as \"14.50\" 14.50 should get displayed as \"14.50\" 14.05 should get

相关标签:
4条回答
  • 2021-01-15 05:27

    I don't think you'll be able to do that without some sort of conditional formatting, because you want the formatting to do different things in different cases.

    If you'd settle for 14.5 instead of 14.50, then you'd be OK with the 0.## syntax, but I can't think of a way to do it.

    0 讨论(0)
  • 2021-01-15 05:30

    Yes. You can use the "G" format specifier. For samples, see String.Format's documentation.

    For example:

    decimal value = 14.05m;
    string result = String.Format("{0:G}", value); // "14.05"
    
    value = 14m;
    result = String.Format("{0:G}", value); // "14"
    
    0 讨论(0)
  • 2021-01-15 05:33

    You could use something like: FormatNumber(VariableToBeFormatted, 2).Replace(".00", String.Empty)

    0 讨论(0)
  • 2021-01-15 05:35

    Follow Reed's answer and add a check after that:

    resultArray = result.Split('.');
    
    if (resultArray.Length > 1 && resultArray[1].Length != 2)
        result = String.Format("{0.00}", value);
    

    Not exactly elegant, but will get you the result you desire.

    This is assuming the person saying it doesn't apply to 14.5 is correct in the comments.

    0 讨论(0)
提交回复
热议问题