How to Format a String to a Two Decimal Places in ASP.NET Core 3.1 MVC View ()

Question: How do you format a String or Number to two decimal places in Asp.Net Core 3.1 View C# 8? Am getting "No Overload for method 'ToString' takes 1 argument.

Please Login to see the rest of the answer

Answer: You can format numbers to Two Decimal places by using Sting.Format like below:

//If you want to format a string/number in a View (Presentation layer)
Or Simply
@string.Format("{00:C0}", YourVariable.ToString())
//Other way to achieve the same results
  • Make sure that you convert the string or number into decimal in your controller for the above functions to work in the View.
  • The other way of making sure that decimal number is formatted to decimal places is by rounding up the decimal number to desired decimal places. Simply type: Math.Round(YourDecimalNumber,2) in the case above, you will be rounding up to the nearest two decimal places.
  • If you want to have commas in the thousands when you are working with Money, simply add

    String.Format("{0:n}",YourNumberYouWantToFormat); //Prints 5,678.88

    [Note]: Leave a comment below so that other Developers can be assured the solution helped you.

Write an Article
If you log in, you will be notified when someone leaves a comment.

Other users would like to know if this solution helped you.

Azfar Hafiz said:

Thank you for the help!

© 2022 - ErnesTech - Privacy