Hello and welcome to our community! Is this your first visit?
Enjoy an ad free experience by logging in. Not a member yet? Register.

# Thread: Get Total

1. ## Get Total

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

• 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.

Code:
```<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

• ## Users who have thanked Philip M for this post:

tqmd1 (12-27-2011)

• Thank you very much sir,
The problem is solved now
Could you please tell me more about replace function in line below

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

• Originally Posted by tqmd1
Thank you very much sir,
The problem is solved now
Could you please tell me more about replace function in line below

Code:
`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().

•

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•