Link to home
Start Free TrialLog in
Avatar of the-miz
the-miz

asked on

sum of numbers some of which are negative

I an trying to run a bunch of input fields with numbers through jquery to get their sum but it does not seem to work with negative numbers. If I put a negative number in the first input field I get "NaN".

Basically my script is upon keyup (changing a value in an input), it will automatically pull all the numbers from the same column and drop in the total a the bottom.

Why am I having problems getting a sum of numbers with negatives?

$.fn.sumValues = function() {
	var sum = 0; 
	this.each(function() {
		sum += Number($(this).val());
	});
	return sum;
};

Open in new window

Avatar of Meir Rivkin
Meir Rivkin
Flag of Israel image

try parseInt:
$.fn.sumValues = function() {
	var sum = 0; 
	this.each(function() {
var val = $(this).val();
if(val != ""){
		sum += parseInt(val);
}
	});
	return sum;
};

Open in new window

Avatar of the-miz
the-miz

ASKER

Guess I should have mentioned I tried parseInt but it does the same thing.  I am working with currency values which may include cents. The number that is being pushed through the jquery looks like 1234.12 (for example) or -1234.12 (for a negative example).  It either comes out as 0 or NaN
try using parseFloat instead of parseInt
Avatar of the-miz

ASKER

parseFloat returns NaN
what is the value passed to parseFloat which returns NaN?
parseFloat works with both negative/positive decimal numbers
Avatar of the-miz

ASKER

Sorry sedgwick, turns out its actually passing the full currency value including $ and commas

Should of caught that.
awesome, do u need any further help?
do u know how to get rid of the $ sign?
Avatar of the-miz

ASKER

The number is being passed as $1,234.12 so I need it to be 1234.12 (or negative depending on the value).  Also, do you still recommend using parseFloat?
On the outside chance that PHP is involved here, you can sanitize the numbers with a regular expression to remove the non-numeric elements (everything that is not a number, a dot or a dash). Something like this...

$money = '$2.54';
$numbr = preg_replace('/[0-9\.\-]/', NULL, $money);
var_dump($money, $numbr);

Open in new window

Avatar of the-miz

ASKER

Does this look good?

$.fn.sumValues = function() {
	var sum = 0; 
	var pattern         = /[^0-9.-]+/g;
	this.each(function() {
		var num = $(this).val();
		sum += parseFloat(num.replace(pattern,''));
	});
	return sum;
};

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Meir Rivkin
Meir Rivkin
Flag of Israel image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Try this :
$.fn.sumValues = function() {
	var sum = 0; 
	this.each(function() {
		sum += $(this).val() * 1;
	});
	return sum;
};

Open in new window