Skip to content

Instantly share code, notes, and snippets.

@shwoodard
Created March 16, 2009 22:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shwoodard/80116 to your computer and use it in GitHub Desktop.
Save shwoodard/80116 to your computer and use it in GitHub Desktop.
(function () {
$ns('mnbb.global');
var Util = mnbb.global.Util = function () {
var DECIMAL_SEP = '.';
var THOUSANDS_SEP = ',';
function eachIsNumber (strs) {
for(var i = 0; i < strs.length; i++ ) {
if (isNaN(strs[i])) {
return false;
}
}
return true;
}
return {
parseToCurrency: function (str) {
if (str.length === 0) {
return 'error';
}
var result = '';
var pieces = str.split(DECIMAL_SEP);
if (pieces.length > 2) {
return 'error';
}
var thousandsPieces = pieces[0].split(THOUSANDS_SEP);
if (!eachIsNumber(thousandsPieces)) {
return 'error';
}
if (pieces.length == 1 || pieces[1].length === 0) {
result = pieces[0] + '.00';
} else if (pieces.length == 2) {
var decimal = pieces[1];
if (isNaN(decimal)) {
return 'error';
}
if (decimal.length >= 2) {
decimal = decimal.substr(0,2);
result = pieces[0] + '.' + decimal;
}
if (decimal.length === 1) {
result = pieces[0] + '.' + pieces[1] + '0';
}
}
return result;
}
};
}();
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment