When you think ASP, think...
Recent Articles
All Articles
ASP.NET Articles
ASPFAQs.com
Message Board
Related Web Technologies
User Tips!
Coding Tips

Sections:
Sample Chapters
Commonly Asked Message Board Questions
JavaScript Tutorials
MSDN Communities Hub
Official Docs
Security
Stump the SQL Guru!
XML Info
Information:
Feedback
Author an Article
Technology Jobs
ASP ASP.NET ASP FAQs Message Board Feedback ASP Jobs

The 4 Guys Present: ASPFAQs.com

Jump to a FAQ
Enter FAQ #:
..or see our 10 Most Viewed FAQs.

4GuysFromRolla.com : ASP FAQS : ASP.NET


Question:

How can I format numbers and date/times using ASP.NET? For example, I want to format a number as a currency.


[Print this FAQ]

Answer: One of the nice things about VBScript was its built-in formatting functions, such as FormatCurrency, FormatNumber, FormatDateTime, etc. (For more information on these functions see this FAQ or, better yet, check out the Strings FAQ Category.)

When creating ASP.NET Web pages with VB.NET, you can still use these functions, although you will need to import the Microsoft.VisualBasic namespace. But what if you are using C#, or want to start using the new formatting methods available in .NET? To allow for formatting, the .NET Framework contains a general String.Format static method along with .ToString() methods for each object.

So, first off, you can easily convert a non-string data type to a string by using it's .ToString method. That is, if you wanted to turn a DateTime variable into a string you could do:

'Create a var. named rightNow and set it to the current date/time
Dim rightNow as DateTime = DateTime.Now
Dim s as String 'create a string

s = rightNow.ToString()

This simple code snippet creates a DateTime variable (rightNow) that is assigned the current system date/time. A String variable (s) is then created and assigned the string representation of the DateTime variable.

The .ToString() contains an overloaded variant that accepts a single String parameter. This parameter can be used to specify how to format the DateTime variable. For example, if we wanted to display the date as a three-lettered month namethen the day, and then a comma followed by the year in four digits (like Jan 30, 2002), we could use the .ToString(formatString) method like so:

'Create a var. named rightNow and set it to the current date/time
Dim rightNow as DateTime = DateTime.Now
Dim s as String 'create a string

s = rightNow.ToString("MMM dd, yyyy")

Pretty neat, eh? Of course the question still remains: "How in the world did I know to use MMM to display the three-letter abbreviation of a month? The answer, of course, is to hit the documentation. One thing the .NET Framework has an abundance of is documentation. For a list of special formatting characters for date/time purposes, see DateTimeFormatInfo Class.

Using the overloaded .ToString() method is nice especially when you want to apply a custom format. However there's another way to format through the use of the String class, which contains a Format method. This method takes a format string followed by one to many variables that are to be formatted. The format string consists of "placeholders," which are essentially locations to place the value of the variables you pass into the function. These placeholders assume the form:

{placeholderNumber:formatCharacter}

So if we wanted to format a number into a currency, we could do so by using the following code:

'Create a var. named price that will be formatted as a currency
Dim price as Double = 3.1
Dim s as String 'create a string

s = String.Format("{0:c}", price)

This would output: $3.10 (or perhaps something else, depending on your Web server's global locale information - that is, in China it may display a Yen symbol instead of the dollar sign). In any case, note that the format string contains a placeholder {0:c}, which says to make the 0th variable in the list a currency (the c denoting currency). If we wanted to format multiple variables in one shot we could do so:

s = String.Format("{0:c} on {1:d}", price, rightNow)

would display:
$3.10 on 1/30/02

Note how the first digit in each placeholder specifies what variable in the proceeding list to use. Again, you may be wondering how I knew a c would apply a currency format, or a d would display the date as it did. Again, via the docs. See Standard Numeric Format Strings and Date and Time Format Strings for more information.

The following small ASP.NET Web page demonstrates using the String.Format method to apply some formatting to various variables.

<script language="C#" runat="server">
  void Page_Load(Object sender, EventArgs e)
  {
     double price = 4.56;
     DateTime rightNow = DateTime.Now;
     int bigNumber = Int32.MaxValue;


     lblPrice.Text = String.Format("{0:c}", price);
     lblTime.Text = String.Format("{0:T}", rightNow);
     lblDate.Text = String.Format("{0:d}", rightNow);
     lblBigInt.Text = String.Format("{0:#,###}", bigNumber);
   }
</script>

<html>
<body>

   The price is: <asp:label runat="server" id="lblPrice" />
   <p>
   The time is: <asp:label runat="server" id="lblTime" />
   <p>
   The date is: <asp:label runat="server" id="lblDate" />
   <p>
   The biggest 32-bit integer is
   <asp:label id="lblBigInt" runat="server" />
</body>
</html>

The output for the above Web page would be:

The price is: $4.56

The time is: 12:14:52 PM

The date is: 1/19/2002

The biggest 32-bit integer is 2,147,483,647

Happy Programming!


FAQ posted by Scott Mitchell at 1/19/2002 3:12:07 PM to the ASP.NET category. This FAQ has been viewed 964,702 times.

Do you have a FAQ you'd like to suggest? Suggestions? Comments? If so, send it in! Also, if you'd like to be a FAQ Admin (creating/editing FAQs), let me know! If you are looking for other FAQs, be sure to check out the 4Guys FAQ and Commonly Asked Messageboard Questions!

Most Viewed FAQs:

1.) How can I format numbers and date/times using ASP.NET? For example, I want to format a number as a currency. (761643 views)
2.) I am using Access and getting a 80004005 error (or a [Microsoft][ODBC Microsoft Access Driver] The Microsoft Jet database engine cannot open the file '(unknown)' error) when trying to open a connection! How can I fix this problem? (207777 views)
3.) How can I convert a Recordset into an array? Also, how can I convert an array into a Recordset? (202549 views)
4.) How can I quickly sort a VBScript array? (196039 views)
5.) How can I find out if a record already exists in a database? If it doesn't, I want to add it. (156019 views)
6.) How do I display data on a web page using arrays instead of Do...While...MoveNext...???... (152331 views)
7.) When I get a list of all files in a directory via the FileSystemObject, they aren't ordered in any reasonable way. How can I sort the files by name? Or by size? Or by date created? Or... (140381 views)
8.) For session variables to work, must the Web visitor have cookies enabled? (110162 views)
9.) Can I send emails without using CDONTS? (107083 views)
10.) How can I take the result of a SELECT...MULTIPLE or a group of same-named checkboxes and turn it into a query? That is, if the user selects 3 answers, how can I construct a query that looks for all 3? (106308 views)
Last computed at 9/17/2007 3:22:00 AM

Software Developer / Programmer - Distributed Systems (NYC)
Next Step Systems
US-NY-New York

Justtechjobs.com Post A Job | Post A Resume


ASP.NET [1.x] [2.0] | ASPMessageboard.com | ASPFAQs.com | Advertise | Feedback | Author an Article