How to convert the following decimal numbers? to String ("F2")

Do I have a decimal place? Amount

In my model, I have a value like @ item.Sales, which I am trying to write as @ item.Sales.ToString ("F2").

I have a message error Error 1 No overload for 'ToString' method takes 1 argument

How can i achieve the above

+5
source share
3 answers

If it's a decimal with a zero value, you need to get a nonzero value first:

@item.Sales.Value.ToString("F2")

Of course, this will throw an exception if @item.Salesit is actually a null value, so you need to check this first.

+12
source

,

  public static class DecimalExtensions
  {
    public static string ToString(this decimal? data, string formatString, string nullResult = "0.00")
    {
      return data.HasValue ? data.Value.ToString(formatString) : nullResult;
    }
  }

:

  decimal? value = 2.1234m;
  Console.WriteLine(value.ToString("F2"));
+2
if( item.Sales.HasValue )
{
    item.Sales.Value.ToString(....)
}
else
{
 //exception handling
}
+1

All Articles