开发者

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

开发者 https://www.devze.com 2023-02-13 16:32 出处:网络
I have Decimal? Amount In my model I have a value as @item.Sales, which I`m trying to write as @item.Sales.ToString(\"F2\").

I have Decimal? Amount

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

I`m having the message error Error 1 No overload for method 'ToString' takes 1 arguments

How can 开发者_运维百科I achieve the above


If it's a nullable decimal, you need to get the non-nullable value first:

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

Of course, that will throw an exception if @item.Sales is actually a null value, so you'd need to check for that first.


You could create an Extension method so the main code is simpler

  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;
    }
  }

And you can call it like this:

  decimal? value = 2.1234m;
  Console.WriteLine(value.ToString("F2"));


if( item.Sales.HasValue )
{
    item.Sales.Value.ToString(....)
}
else
{
 //exception handling
}


Use the unary ? operator to run .ToString() only when there's an object

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

Or use the double ?? operator thus makes it non-nullable:

@((item.Sales??0).ToString("F2"))

This is better than @item.Sales.Value.Tostring("F2") because if you don't check for null value before using .ToString("F2") the code will break at runtime.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号