...

View Full Version : Get Total



tqmd1
12-27-2011, 10:00 AM
Dear Coders

var amount1=12,345,678.10
var amount1=87,246,125.00

I want to sum amount1+amount2 as 99,591,803.10

Please help

Philip M
12-27-2011, 10:49 AM
I thought we had dealt with this in your previous thread. You seem to have not understood that "numbers" formatted with commas are not arithmetic numbers but strings and cannot be added. So var amount1=12,345,678.10 returns an immediate error. You must convert your string values back into numbers, add them, and then reformat the result.



<script type = "text/javascript">

var amount1="12,345,678.10"; // numbers formatted with commas are strings
var amount2= "87,246,125.00";
var a = amount1.replace(/[^0-9\.]/g,"");
var b = amount2.replace(/[^0-9\.]/g,"");
var nStr = (Number(a) + Number(b)).toString();
var rgx = /(\d+)(\d{3})/;
while (rgx.test(nStr)) {
nStr = nStr.replace(rgx, '$1,$2');
}
//nStr = "$" + nStr; // if $ prefix required
if (nStr.indexOf('.') == -1) { // if whole number add .00
nStr = nStr + ".00";
}
nStr = nStr.replace(/(\.\d)$/,"$10"); // if only one DP add another 0

alert (nStr);

</script>


Whatever it is that he's got, he's got it. - Sports Commentator

tqmd1
12-27-2011, 12:16 PM
Thank you very much sir,
The problem is solved now
Could you please tell me more about replace function in line below


var a = amount1.replace(/[^0-9\.]/g,"");

Philip M
12-27-2011, 03:32 PM
Thank you very much sir,
The problem is solved now
Could you please tell me more about replace function in line below


var a = amount1.replace(/[^0-9\.]/g,"");

It means strip out everything from the string except digits 0-9 and decimal point (in this instance meaning the commas). The result is still a string, but is capable of being turned into a number (which can be added to another number) using Number().



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum