Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

asp.net-mvc

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

like image 929
learning Avatar asked Feb 28 '11 09:02

learning


People also ask

How do you convert a decimal to a string?

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.

How to display Double value in string c#?

ToString() Method is used to convert the numeric value of the current instance to its equivalent string representation.


2 Answers

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.

like image 197
Jon Skeet Avatar answered Nov 06 '22 05:11

Jon Skeet


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"));
like image 22
Shiv Kumar Avatar answered Nov 06 '22 05:11

Shiv Kumar