2

在我的网页中,我有一个货币格式的总数,可以是正数或负数。

Example $5.50 or $(5.50). 

该值只不过是跨度标记中包含的文本。我正在尝试读取该值并将其转换为 js 中的数值,然后我可以对其执行数学计算。

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

我编写了以下正则表达式脚本来处理将负货币值转换为数值

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

我有以下方法来处理检索和转换值。

//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);
}

我不清楚如何首先测试该值是否为负,其次如果为负,则将该值替换为正则表达式结果。

4

2 回答 2

1

注意:否定类可以真正解决正则表达式问题,IMO。不,我不在乎 JSLint 对此事的看法。使用 '。' 缓慢而笨拙,为特定的 lint gotcha 给出的理由是荒谬的。

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;
}
于 2012-10-02T18:52:11.840 回答
0
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) );
于 2012-10-02T18:50:09.017 回答