Skip to main content

Format a number as US currency [JavaScript]

A recent project I worked on allowed customers to request cloud computing resources. One of the requirements was to display the cost for each resource amount and the totals for one and two years for the resources the customer was requesting. In the United States, numbers are formatted with a period for the decimal mark and a comma as the thousands separator, e.g. 1,234,567.89.

The function below is going to:
  1. Assume that the input is either an unsigned integer or a float, ex. 1234567 or 1234567.90.
  2. Insert a "," delimiter every third digit.
  3. Optionally, add a currency symbol to the returned string.
Let’s review:
  • On lines 2 - 4 I defined some default values.
  • On line 6 I defined a closure called formatNumber. The logic in the closure is going to format the number string.
  • Starting at line 28 I am making sure that when the formatCostNumber function is called it does receive a value to format, and that value is numeric; next before formatting said value, I convert it to a string and determine if it contains a period. I only want to format the portion of the string before the period.
  • Last, on line 43, before returning the formatted number string, I check if I need to add a currency symbol.

Now, let's take a look at the logic of the formatNumber closure.
  1. Line 7 - I make sure that the string to format has at least four characters. There is no reason to format something like "123", which will only result in ",123".
  2. Line 10 - I create a for loop which is going to run for the length of the string (i). This variable will change as the string is modified. The loop will count down to 1. Going in a descending order will allow me to move from right to left as I parse the string. I am counting down to 1 instead of 0 to avoid output like ",123,456". I am also adding two more parameters: hops, which will track the number of turns since last "," insertion; and turns, which will track the actual number of times the loop has run.
  3. Line 13 - I check if there have been 3 turns since the last insertion and the if the character at the current position of the string is not already a ",". If these conditions are not met then I am going to increment the hops by 1 and loop around.
  4. Line 14 - If my conditions are met, I am going to insert the thousands' delimiter by concatenating two different strings with the delimiter in between. The first string being the portion of the subject string up to the current position, and the second string being everything after the current position.
  5. Line 17 - I reset back to zero the count since the last insertion.
  6. Line 18 - I update the string index position (i) by subtracting actual loop count (turns) from the actual length of the string I just modified. This will prevent results like "12,34,567".

Note: The delimiter insertion loop can be optimized by directly incrementing by 3 after inserting the thousands' delimiter and updating the string length. This will allow for dropping the hops and turns variable, but it will require a check for how many characters a left to the front of the string to avoid ending up with ",123,456".


Popular posts from this blog

Format MAC Address [JavaScript]

I am currently working on a project which will allow users to register their Wi-Fi enabled, non-web browser enabled, devices on the network. These are devices like printers, Apple TV, and Xbox*. One of the data points that have to be collected from the user is the device MAC address. The project customer wants that address to be properly formatted when they see it in the support ticket.

We have several options. We can format the address either on the back-end after the form has been submitted. Or we can format it on the front end via a separate text field for each character pair, but that is too many fields to handle. A better solution is to use a single field and format the user input at the time of input or upon submit. In those cases, the former is better because the data will already be formatted when the overall form input is being validation after the user clicks the “Submit” button.

We are going to format the user input as it is being provided, thus having proper data when vali…

SNOOZ: Sound. Sleep.

I was on the Snooz Kickstarter page today, revisiting the project’s details and timeline progress. The device, which is a white-noise generating machine, recently became available for pre-order. Snooz is meant to be an alternative to having a TV or a stationary fan running at bed time. In my case, I bought it for my wife so we can get the TV out of the bedroom.

Whilst on the comments page I read the following comment, posted recently by Ken Tran:

I'm not a fan of the new fabric design. ...
I must disagree. If you take a look at the original design, which is all plastic and no style, I must say it is fugly. It is all utilitarian - not something I rally want to look at or see when I walk into the room. The final design, seen on the right, is something that beacons to be explored, looked at, utilized.

I am a big fan of Bang & Olufsen. They use fabric from Kvadrat in their line of products. Incorporating soft materials like fabric or leather in something which is meant to be place…

Balloon Flowers of 2014

We have Balloon Flowers (platycodon grandiflorus) in a half barrow pot. They are one of my favorite flowers that we have around the house. Simply because of how the flower forms. It starts as a small ball, which slowly grows into the shape of a hot air balloon, and once it opens it looks like it had exploded.

[gallery type="rectangular" link="file" ids="2611,2612,2622,2615,2613,2614,2616,2617,2618,2619,2610,2620,2621"]

I planted the flowers from the pictures above about seven years, ago.