How to convert the following decimal? to String("F2")
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"));