# 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.

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.