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.


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)
@ViewBag.YourVariable.ToString("0.00.##")
Or Simply
@string.Format("{00:C0}", YourVariable.ToString())
//Other way to achieve the same results
Convert.ToDecimal(TheIntegerValueYouWantToShowAsDecimal).Value.ToString("00.00.##");
  • 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.




Azfar Hafiz said:

Thank you for the help!

Posted On: January 14, 2022 2:50:46 AM

© 2024 - ErnesTech - Privacy
E-Commerce Return Policy