When you think ASP, think...
Recent Articles
All Articles
ASP.NET Articles [1.x] [2.0]
ASPFAQs.com
Message Board
Related Web Technologies
User Tips!
Coding Tips
Search

Sections:
Book Reviews
Sample Chapters
Commonly Asked Message Board Questions
Headlines from ASPWire.com
JavaScript Tutorials
MSDN Communities Hub
Official Docs
Security
Stump the SQL Guru!
Web Hosts
XML Info
Information:
Advertise
Feedback
Author an Article
Technology Jobs

















internet.com
IT
Developer
Internet News
Small Business
Personal Technology
International

Search internet.com
Advertise
Corporate Info
Newsletters
Tech Jobs
E-mail Offers
ASP ASP.NET ASP FAQs Message Board Feedback ASP Jobs
Print this page.

Windows Systems Administrator
Jupitermedia
US-CT-Darien

Justtechjobs.com Post A Job | Post A Resume

Published: Thursday, November 12, 1998

WebDaily: Your daily source for Web Technology Tips and Tricks!


*****************************************************************
Formatting with JavaScript
*****************************************************************

* This article discusses how to format strings and numbers using JavaScript.

Since Internet Explorer is the only browser which supports VBScript, when developing client-side scripts, using JavaScript is imperative. JavaScript, though, lacks the easy to use formatting features that VBScript inherently provides. There are often times, though, when you need to use JavaScript to output dynamic values to form elements, or through alerts, and you must use JavaScript's formatting features. This article intends to step through some of the techniques you can use in JavaScript to format numbers and strings.

NUMBERS:
========
One nice thing about VBScript is its FormatNumber function. Using this function you can specify how to display a number, and how many decimal places to use, if a leading zero is to be included for fractional numbers, and if you wish to use parenthesis for negative numbers. Let's write this function in JavaScript:

   function FormatNumber(num, decimalNum, bolLeadingZero, bolParens)
   /* IN - num:            the number to be formatted
           decimalNum:     the number of decimals after the digit
           bolLeadingZero: true / false to use leading zero
           bolParens:      true / false to use parenthesis for - num

      RETVAL - formatted number
   */
   {
       var tmpNum = num;

       // Return the right number of decimal places
       tmpNum *= Math.pow(10,decimalNum);
       tmpNum = Math.floor(tmpNum);
       tmpNum /= Math.pow(10,decimalNum);

       var tmpStr = new String(tmpNum);

       // See if we need to hack off a leading zero or not
       if (!bolLeadingZero && num < 1 && num > -1 && num !=0)
           if (num > 0)
               tmpStr = tmpStr.substring(1,tmpStr.length);
           else
               // Take out the minus sign out (start at 2)
               tmpStr = "-" + tmpStr.substring(2,tmpStr.length);                        


       // See if we need to put parenthesis around the number
       if (bolParens && num < 0)
           tmpStr = "(" + tmpStr.substring(1,tmpStr.length) + ")";


       return tmpStr;
   }

This function should suit most of your number formatting needs (except for currency issues). This function could be made a little more fail-safe if some priliminary testing was implemented. For example, if decimalNum is less than zero, then we must handle it so not to get a strange result. Here is an example of how you could use the function above:

<SCRIPT LANGUAGE="JavaScript">
var MyNum = -0.314159;
document.write(FormatNumber(MyNum,3,false,true));
</SCRIPT>

This would print (.314) as your output.

STRINGS:
========
With a little ingenuity and code, you can create any string formatting function by knowing just the following two string operators: substring and indexOf. To use any of the string object method or properties, you must create a variable of type String. In the FormatNumber function, I created a variable named tmpStr which was declared as follows:

var tmpStr = new String();

Once you declare a variable as a String object, you can use the appropriate methods. One important method is indexOf. indexOf returns a cbaracter at a passed in position of your string. For example:

tmpStr = String("Hello world!");
document.write(tmpStr.indexOf(4));

would output "o". One important thing to remember about strings in JavaScript is that they are zero-based. The first character in a string is in the zero-th position. So tmpStr.indexOf(4) returns the 5th character, which is "o". The other important string object method, substring, takes two parameters, the start and stop positions. Let's look at a quick example:

tmpStr = String("Hello world!");
document.write(tmpStr.substring(4,8));

would output "o wor". Again, recall that strings are indexed starting at zero, not one. By just using substring and indexOf, you can formulate any string formatting functions. Examples can be seen at the 4 Guys website, http://www.4GuysFromRolla.com

Happy Programming!

*****************************************************************
*****************************************************************
To subscribe to WebDaily, point your browser to:
http://www.4GuysFromRolla.com/webtech/webdaily
*****************************************************************
*****************************************************************

Please forward this information to a friend, including the subscription URL! Happy Programming!


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



JupiterOnlineMedia

internet.comearthweb.comDevx.commediabistro.comGraphics.com

Search:

Jupitermedia Corporation has two divisions: Jupiterimages and JupiterOnlineMedia

Jupitermedia Corporate Info


Legal Notices, Licensing, Reprints, & Permissions, Privacy Policy.

Advertise | Newsletters | Tech Jobs | Shopping | E-mail Offers

Solutions
Whitepapers and eBooks
Microsoft Article: Will Hyper-V Make VMware This Decade's Netscape?
Microsoft Article: 7.0, Microsoft's Lucky Version?
Microsoft Article: Hyper-V--The Killer Feature in Windows Server 2008
Avaya Article: How to Feed Data into the Avaya Event Processor
Microsoft Article: Install What You Need with Windows Server 2008
HP eBook: Putting the Green into IT
Whitepaper: HP Integrated Citrix XenServer for HP ProLiant Servers
Intel Go Parallel Portal: Interview with C++ Guru Herb Sutter, Part 1
Intel Go Parallel Portal: Interview with C++ Guru Herb Sutter, Part 2--The Future of Concurrency
Avaya Article: Setting Up a SIP A/S Development Environment
IBM Article: How Cool Is Your Data Center?
Microsoft Article: Managing Virtual Machines with Microsoft System Center
HP eBook: Storage Networking , Part 1
Microsoft Article: Solving Data Center Complexity with Microsoft System Center Configuration Manager 2007
MORE WHITEPAPERS, EBOOKS, AND ARTICLES
Webcasts
Intel Video: Are Multi-core Processors Here to Stay?
On-Demand Webcast: Five Virtualization Trends to Watch
HP Video: Page Cost Calculator
Intel Video: APIs for Parallel Programming
HP Webcast: Storage Is Changing Fast - Be Ready or Be Left Behind
Microsoft Silverlight Video: Creating Fading Controls with Expression Design and Expression Blend 2
MORE WEBCASTS, PODCASTS, AND VIDEOS
Downloads and eKits
Sun Download: Solaris 8 Migration Assistant
Sybase Download: SQL Anywhere Developer Edition
Red Gate Download: SQL Backup Pro and free DBA Best Practices eBook
Red Gate Download: SQL Compare Pro 6
Iron Speed Designer Application Generator
MORE DOWNLOADS, EKITS, AND FREE TRIALS
Tutorials and Demos
How-to-Article: Preparing for Hyper-Threading Technology and Dual Core Technology
eTouch PDF: Conquering the Tyranny of E-Mail and Word Processors
IBM Article: Collaborating in the High-Performance Workplace
HP Demo: StorageWorks EVA4400
Intel Featured Algorhythm: Intel Threading Building Blocks--The Pipeline Class
Microsoft How-to Article: Get Going with Silverlight and Windows Live
MORE TUTORIALS, DEMOS AND STEP-BY-STEP GUIDES