Showing posts with label decimal to string. Show all posts
Showing posts with label decimal to string. Show all posts

Friday, April 14, 2017

Set variable formatting in MVC razor

Issue

This was a real challenge to figure out.  It seems pretty straight forward but it is the details that eat up so much time.  I had a number of decimal data types that represented currency.  I wanted them displayed at local currency.  I thought .Net has this down and lots of people have done this already.  Easy, right?

Well, yes and no.  I went to implement and found most examples and answers incomplete.

Here is what you need.  In the razor view, add references to the threading and globalization namespaces:

@using System.Threading
@using System.Globalization

In your markup, use the String.Format and CultureInfo methods to get your formatting correct.

 var tDebit = String.Format(new CultureInfo("en-US"), "{0:C}", nDebit);
 @Html.Raw(tDebit);



Sources

  1. https://msdn.microsoft.com/en-us/library/bz9tc508.aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-3
  2. http://stackoverflow.com/questions/10740828/format-decimal-to-currency-in-viewbag
  3. https://msdn.microsoft.com/en-us/library/dwhawy9k.aspx