JavaScript – Add Commas To Numbers

At times, I have had to add commas to numbers in order to make them look better in different applications. Even though there isn’t a native way to do this in JavaScript, the code can be quite short, sweet and to the point:

function addCommas(intNum) {
  return (intNum + '').replace(/(\d)(?=(\d{3})+$)/g, '$1,');
}

The downside of the above function is that it will only work for integers. Here is a function that will get the job done for one number or a string which contains one or more numbers:

function delimitNumbers(str) {
  return (str + "").replace(/\b(\d+)((\.\d+)*)\b/g, function(a, b, c) {
    return (b.charAt(0) > 0 && !(c || ".").lastIndexOf(".") ? b.replace(/(\d)(?=(\d{3})+$)/g, "$1,") : b) + c;
  });
}

First this function forces the parameter that was passed in to become a string. Next, a global replace of a regular expression looking for a four-digit or longer number goes through and inserts the commas in the correct place. After that, the result is returned as a string.

Here are some tests that I ran on the function to make sure that it works correctly:

// Delimit a random number.
alert("Random number:  " + delimitNumbers(Math.random() * (1 << 30)));

// Delimit all powers of 2 (from 2^0 to 2^30) in a string.
var powersOf2 = Array.range(31).map(function(i){return 1 << i});
alert("Powers of 2:\n" + delimitNumbers(powersOf2.join("\n")));

One thing you want to keep in mind if you choose to test the delimitNumbers() function with the above code is the fact that you will need to make sure that Array.range() and Array.prototype.map() are correctly defined. I did my test in the ScriptBox which always uses the newest version of jPaq (currently an alpha of v2.0).

PostgreSQL – String To Rows

Working Solution – Custom Function

I have to say that using PostgreSQL has been great compared to MySQL. Recently, though, I ran into an issue while working with iReports designer. I needed to be able to accept a string of comma-delimited integers and then JOIN on those ID’s. Therefore, I started looking for a good string splitting function. At first I was unable to find a native one so I altered this plpgsql function made by pilcrow and added some documentation:

CREATE OR REPLACE FUNCTION split_to_rows(
	IN in_text TEXT,
	IN in_delimiter VARCHAR(20)
)
RETURNS SETOF TEXT AS $$
---------------------------------------------------------------------------
-- Function Name: split_to_rows
-- In-coming Params:
--   in_text [TEXT]
--   in_delimiter [VARCHAR(20)]
-- Out going Param:
--   TEXT
-- Description:
--   Splits the specified text with the specified delimiter and returns a
--   set of rows.
-- Created On: 2011-05-24
-- Author: pilcrow (http://stackoverflow.com/questions/1986491#1987113)
-- Modified By: Chris West
---------------------------------------------------------------------------
  DECLARE
    elems text[];      
  BEGIN
    elems := string_to_array(in_text, in_delimiter);
    FOR i IN array_lower(elems, 1) .. array_upper(elems, 1) LOOP
      RETURN NEXT elems[i];
    END LOOP;
    RETURN;
  END
$$ LANGUAGE 'plpgsql';

The following is an example of using this new function to convert a string of numbers into rows of numbers as integers.

SELECT CAST(split_to_rows('1,2,3,4,5,6', ',') AS INTEGER) AS id;

The Better Solution – Native PostgreSQL Function

After looking into other native solutions, I finally found the regexp_split_to_table function. This is basically called in the same way as pilcrow’s, but with one major difference: you can use regular expressions to split the string into rows. Here is an example of using this new function in the same was as I did the split_to_rows function:

SELECT CAST(regexp_split_to_table('1,2,3,4,5,6', ',') AS INTEGER) AS id;

Escape & Unescape – Deprecated?

Two of the most widely used JavaScript functions that are now deprecated are the escape() and unescape() functions. This means that in order to ensure that your code will continue to work in all future browsers, you should use one of the alternative functions as was indicated on MDN:

  • encodeURI()
  • decodeURI()
  • encodeURIComponent()
  • decodeURIComponent()

What To Do When They Are No More

Since these functions may not always exist, I decided to write the necessary JavaScript code to make sure they can continue to be used:

(function() {
var objGlobal = this;
if(!(objGlobal.escape && objGlobal.unescape)) {
  var escapeHash = {
    _ : function(input) {
      var ret = escapeHash[input];
      if(!ret) {
        if(input.length - 1) {
          ret = String.fromCharCode(input.substring(input.length - 3 ? 2 : 1));
        }
        else {
          var code = input.charCodeAt(0);
          ret = code < 256
            ? "%" + (0 + code.toString(16)).slice(-2).toUpperCase()
            : "%u" + ("000" + code.toString(16)).slice(-4).toUpperCase();
        }
        escapeHash[ret] = input;
        escapeHash[input] = ret;
      }
      return ret;
    }
  };
  objGlobal.escape = objGlobal.escape || function(str) {
    return str.replace(/[^\w @\*\-\+\.\/]/g, function(aChar) {
      return escapeHash._(aChar);
    });
  };
  objGlobal.unescape = objGlobal.unescape || function(str) {
    return str.replace(/%(u[\da-f]{4}|[\da-f]{2})/gi, function(seq) {
      return escapeHash._(seq);
    });
  };
}
})();

Reference

I created these functions based on information found at DevGuru.com.