Link to home
Start Free TrialLog in
Avatar of Bharat Guru
Bharat Guru

asked on

how to sum two numbers in c# page using javascript


i want to add two numbers that are generated dynamically which contain symbols like dollar and comma.

ex:
 [txtField1] + [txtField2] =  [txtsum]
$1,111.11 + $1,111.11 = 2222.22

function calsum()
{
   var objField1 = document.getElementByUD('txtField1');
   var objField2 = document.getElementByUD('txtField2');

  var sum1 = parseFloat(objField1.value) + parseFloat(objField2.value);

   document.getElementByUD('txtsum')  = sum1.value;

}
Avatar of brd24gor
brd24gor

You can use String.Replace to filter out commas and dollar signs, do the float conversion, then add them up.

txtField1.Replace("$","");
txtField2.Replace(",","");
Avatar of Shaun Kline
In javascript, you would use:

var sum1 = parseFloat(objField1.value.replace(/\$|\,/g,'')) + parseFloat(objField2.value.replace(/\$|\,/g,''));
Avatar of Bharat Guru

ASKER

when txtField1 or txtField2 is null then result is shown as NaN.  
when field1 or field2 are null then result should be ''  (empty)
Try this out:
function calsum()
{
	var objField1 = document.getElementById('txtField1').value.replace(/[^0-9.]/g, '');
	var objField2 = document.getElementById('txtField2').value.replace(/[^0-9.]/g, '');

	var sum1 = (objField1 == null ? 0 : parseFloat(objField1)) + (objField2 == null ? 0 : parseFloat(objField2));

	document.getElementById('txtsum').value = sum1;
}

Open in new window

This would be a bit safer, I think:
function calsum()
{
	var objField1 = document.getElementById('txtField1').value.replace(/[^0-9.]|\.(?=\d*\.)/g, '');
	var objField2 = document.getElementById('txtField2').value.replace(/[^0-9.]|\.(?=\d*\.)/g, '');

	var sum1 = (objField1 == null ? 0 : parseFloat(objField1)) + (objField2 == null ? 0 : parseFloat(objField2));

	document.getElementById('txtsum').value = sum1;
}

Open in new window

minus addition doesn't work
 5   -5   = shows 10 instead of 0
ASKER CERTIFIED SOLUTION
Avatar of kaufmed
kaufmed
Flag of United States of America 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
Thanks a lot perfect
NP. Glad to help  :)