Code Junkie
Code Junkie

Reputation: 7788

Javascript to test value against regex and later value if needed

in my webpage I have a total in currency format that can either be positive or negative.

Example $5.50 or $(5.50). 

This value is nothing other than text contained within a span tag. I'm trying to read the value and convert it into a numeric value in js where I can then perform math calculations against it.

Example $5.50 -> 5.50 and $(5.50) -> -5.50

I have written the following regex script to handle converting negative currency values into numeric values

var regex = /^\$*?\((\d+(\.)?(\d+)?)\)$/

I have the following methods to handle retrieving and converting the value.

//retrieve value from template
$.fn.fieldVal = function () {
    var val;

    if ($(this).is(':input')) {
        val = $(this).val();
    } else {
        val = $(this).text();
    }    

    return convertCurrencyToNumeric(val);

};

//convert currency to numeric value
function convertCurrencyToNumeric(n) {
    var regex = /^\$*?\((\d+(\.)?(\d+)?)\)$/

    n = n.replace(/[^0-9-\.]/g, '');

    if(isNumber(n)) {
        n = parseFloat(n);
        return n;
    }
    return 0;
}

//test if numeric
function isNumber(n) {
    return !isNaN(parseFloat(n)) && isFinite(n);
}

I'm not clear how to first test if the value is negative and secondly if negative, replace the value with regex outcome.

Upvotes: 2

Views: 213

Answers (2)

Erik  Reppen
Erik Reppen

Reputation: 4625

Note: Negating classes can really clear up regEx problems, IMO. And no, I don't care what JSLint's opinion on the matter is. Using '.' is slow and clumsy and the rationale given for that particular lint gotcha is absurd.

function convertCurrency(str){
    var negMatch = ( str.match(/(^\$-|^-\$|^$\()/g) ), //handles -$5.05 or $-5.05 too
    str = str.replace(/[^\d.]/g,''), //anything that's not a digit or decimal point
//gotcha, Europeans use ',' as a decimal point so there's a localization concern
    num = parseFloat(str);

    if(negMatch){ num *= -1; }

    return num;
}

Upvotes: 1

epascarello
epascarello

Reputation: 207531

function getMoney (str) {
   var amount = str.replace(/(\$)(\()?(\d+\.\d{0,2})\)?/, 
      function (match, dollar, neg, money) {
         var negSign = neg ? "-" : ""; 
         return negSign + money;
      }
   );
   return parseFloat(amount);
}

var str1 = "$(5.50)";
var str2 = "$5.50";

console.log( getMoney(str1) );
console.log( getMoney(str2) );

Upvotes: 0

Related Questions