TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
 Specialized Dev Zones Research Center eBook Library .NET Java C++ Web Dev Architecture Database Security Open Source Enterprise Mobile Special Reports 10-Minute Solutions DevXtra Blogs Slideshow

Language: Client Scripting
Expertise: Beginner
Jul 8, 1997

### WEBINAR:On-Demand

Building the Right Environment to Support AI, Machine Learning and Deep Learning

# Representing Numeric Values in US Currency Format

Question:

Many people have been asking how to do this. Since JavaScript does not have built-in methods for converting numbers to currency-formatted strings, the only option left is to make a function that does it for us -- which I have already done for you.

The name of the function is `toUSCurrency`. It takes a number or string as input and returns a new string representing the original input as US currency. I present it to you in an edit-box so that you can cut and paste it into your own JavaScript programs:

 function toUSCurrency (input) { // Make sure input is a string: input += ""; // Keep original copy of input string: var original_input = input; // Strip leading dollar sign if necessary: if (input . charAt (0) == "\$") input = input . substring (1, input . length); else if ( input . substring (0, 2) == "-\$" || input . substring (0, 2) == "+\$" ) input = input . charAt (0) + input . substring (2, input . length); // Get float value: var amount = parseFloat (input); // Return unmodified input if we weren't able to convert it: if (isNaN (amount)) return original_input; // Express amount in pennies, rounded to the nearest penny: amount = Math . round (100 * amount); // Prepare to add a US currency prefix: var prefix = "\$"; if (amount < 0) { prefix = "-" + prefix; amount = - amount; } // Convert amount to string and pad with leading zeros if necessary: var string; if (amount < 10) string = "00" + amount; else if (amount < 100) string = "0" + amount; else string = "" + amount; // Insert prefix: string = prefix + string; // Insert decimal point before last two digits: string = string . substring (0, string . length - 2) + "." + string . substring (string . length - 2, string . length); // Return formatted currency string: return string; }
By the way, this function was designed to withstand abuse. If the number or string passed in cannot be converted, then a string representing the original, unmodified input is returned instead.

The following form is provided so that you can experiment with the `toUSCurrency` function and determine if it suits your needs.

 Input: Output: `Output = toUSCurrency (Input);`
If you like `toUSCurrency`, please feel free to use it in your own JavaScript programs.
DevX Pro

 Submit a Tip Browse "Web Development" Tips Browse All Tips
Comment and Contribute

(Maximum characters: 1200). You have 1200 characters left.

Thanks for your registration, follow us on our social networks to keep up-to-date