Trouble with javascript subtraction
I'm working on a simple subtraction problem, but unfortunately it keeps returning NaN
Here is the function
function subtraction(a, b) {
var regexp = /[$][,]/g;
a = a.replace(regexp, "");
b = b.replace(regexp, "");
var _a = parseFloat(a);
var _b = parseFloat(b);
return _a - _b;
}
And here is how I'm calling it.
txtGoodWill.value = subtraction(txtSellingPrice.value, txtBalanceSheet.value);
The numbers that get submitted to 开发者_如何学JAVAthe function are ONLY Currency (IE: $2,000
or $20
, etc)
Now I know that I cannot subtract numbers with a $
or a ,
, but I can't for the life of me figure out why they are getting evaluated in the equasion.
Your regular expression only matches if a $
is directly followed by ,
. Use /[$,]/g
instead to match all occurrences of either of the two characters.
I think you want var regexp = /[$,]/g;
(both the $
and ,
inside the same set of square brackets).
精彩评论