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
To convert a Decimal value to its string representation using a specified culture and a specific format string, call the Decimal. ToString(String, IFormatProvider) method.
ToString() Method is used to convert the numeric value of the current instance to its equivalent string representation.
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 you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With