2 Replies - 5787 Views - Last Post: 26 April 2013 - 01:58 PM

#1 troyb408  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 69
  • Joined: 18-August 12

Format number string

Posted 20 March 2013 - 02:12 PM

Here is a tricky one -

I have a linq command that is pulling from the DB. This is then formatted in to a string array returned to the view via json. My issue is my number formatting. Some of the numbers are in the billions / millions etc. What I would like to do is format the column to display 15B or 15M depending on how much it really is. Here is the code:

I've tried using #,##0,,,B / #,#M etc but it its not a billion or million the column display 0B 0M and user needs to know then how many Billions /Millions it is.

 var rows = from d in dt
            select new string[] { d.industry_code.ToString() , d.industry_desc, d.SpendingTotal.ToString("0,00.00") , d.SpendingDoD.ToString("#,#M"), d.Empl12Mo.ToString("0,0.00"), d.AnnAvgWage.ToString("0,0.00")                            
                             };



Is This A Good Question/Topic? 0
  • +

Replies To: Format number string

#2 Robin19  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 267
  • View blog
  • Posts: 547
  • Joined: 07-July 10

Re: Format number string

Posted 26 April 2013 - 01:47 PM

You might try writing your own ICustomFormatter. This is some ugly, untested code to give you an idea.

public class LargeNumberFormatter : ICustomFormatter
{
   public string Format(string format, object arg, IFormatProvider formatProvider)
   {
      int amount = Int32.Parse(arg.ToString());

      if (format.Length() > 9)
      {
         return string.Format("{0.00}B", amount);
      }
      if (format.Length() > 6)
      {
         return string.Format("{0.00}M", amount);
      }
      return amount.ToString();
   }
}


var rows = from d in dt
           select new string[] { d.industry_code.ToString() , d.industry_desc, d.SpendingTotal.ToString("0,00.00") , string.Format(new LargeNumberFormatter(), d.SpendingDoD, null), d.Empl12Mo.ToString("0,0.00"), d.AnnAvgWage.ToString("0,0.00")                            
                            };

This post has been edited by Robin19: 26 April 2013 - 01:50 PM

Was This Post Helpful? 0
  • +
  • -

#3 andrewsw  Icon User is online

  • Fire giant boob nipple gun!
  • member icon

Reputation: 3196
  • View blog
  • Posts: 10,703
  • Joined: 12-December 12

Re: Format number string

Posted 26 April 2013 - 01:58 PM

?(24000000000D).ToString("#,,, B")
"24 B"

but if you have billions and millions in the same column then it's a little more involved. (Add a comma depending on your locale :))

This post has been edited by andrewsw: 26 April 2013 - 02:01 PM

Was This Post Helpful? 1
  • +
  • -

Page 1 of 1