How do I display a decimal value to 2 decimal places?

前端 未结 17 2174
没有蜡笔的小新
没有蜡笔的小新 2020-11-21 23:24

When displaying the value of a decimal currently with .ToString(), it\'s accurate to like 15 decimal places, and since I\'m using it to represent dollars and ce

17条回答
  •  灰色年华
    2020-11-22 00:17

    There's already two high scoring answers that refer to Decimal.Round(...) but I think a little more explanation is needed - because there's an unexpected important property of Decimal that isn't obvious.

    A Decimal 'knows' how many decimal places it has based upon where it came from

    For instance the following may be unexpected :

    Decimal.Parse("25").ToString()          =>   "25"
    Decimal.Parse("25.").ToString()         =>   "25"
    Decimal.Parse("25.0").ToString()        =>   "25.0"
    Decimal.Parse("25.0000").ToString()     =>   "25.0000"
    
    25m.ToString()                          =>   "25"
    25.000m.ToString()                      =>   "25.000"
    

    Doing the same operations with Double will give no decimal places ("25") for each of the above.

    When you want a decimal to 2 decimal places theres about a 95% chance it's because it's currency in which case this is probably fine for 95% of the time:

    Decimal.Parse("25.0").ToString("c")     =>   "$25.00"
    

    Or in XAML you just use {Binding Price, StringFormat=c}

    One case I ran into where I needed a decimal AS a decimal was when sending XML to Amazon's webservice. The service was complaining because a Decimal value (originally from SQL Server) was being sent as 25.1200 and rejected, (25.12 was the expected format).

    All I needed to do was Decimal.Round(...) with 2 decimal places to fix the problem.

     // This is an XML message - with generated code by XSD.exe
     StandardPrice = new OverrideCurrencyAmount()
     {
           TypedValue = Decimal.Round(product.StandardPrice, 2),
           currency = "USD"
     }
    

    TypedValue is of type Decimal so I couldn't just do ToString("N2") and needed to round it and keep it as a decimal.

提交回复
热议问题