Format Currency

by Terrance Smith

HTML

<input id="valMe" type="text" value="1,234.56" />
<button id="formatBtn">Format</button>

JavaScript

String.isNullOrEmpty = function (value) {
   "use strict";
   //Credit to the following for a detailed explaination	
   //http://codereview.stackexchange.com/questions/5572/feedback-on-implementation-of-string-isnullorwhitespace-in-javascript
   return !value;
};

String.isNullOrWhiteSpace = function (value) {
   "use strict";
   if (String.isNullOrEmpty(value)) {
      return true;
   } else if (String.isNullOrEmpty(value.toString().trim())) {
      return true;
   }
   return false;
};

//Used for formatting numbers.
//Removes Extranous characters from numerical strings 
//So they can be used for calculating expressions. 
function Cleanse(x) {
   if (String.isNullOrWhiteSpace(x)) {
      return x;
   } else {
      var i = 0;
      var retval = "";
      for (var i = 0; i < x.length; i++) {
         if (x.charAt(i) !== " " && x.charAt(i) !== "," && x.charAt(i) !== "$" && !String.isNullOrEmpty(x.charAt(i))) {
            retval += x.charAt(i);
         }
      }
      return retval;
   }
}

function formatCurrency(num) {
   //num = isNaN(num) || num === "" || num === null ? 0.00 : num; return addCommas(parseFloat(num).toFixed(2));
   num = isNaN(num) || num === "" || num === null ? 0.00 : num;
   return parseFloat(num).toFixed(2);
}


$("#formatBtn").click(function () {
    var elem = $("#valMe");
    elem.val(Cleanse(elem.val()));
    console.info(formatCurrency(elem.val()))
});