开发者

Add amounts and put in element

I'd like to add two amounts together, each one from a different element, and put them in an other element. The tricky part is to keep the "$" sign and comma (,) in the total amount (or maybe add them to the total amount afterwards?).

Anyone know of a Javascript that can do this?

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Add amounts and put in element</title>
</head>

<开发者_JAVA技巧;body>

<p id="firstAmount">$1,133.79</p>

<p id="secondAmount">$1,900.00</p>

<br />

Total: <p id="totalAmount">$0.00</p>

</body>
</html>

******************** UPDATE 2 **********************

Replace:

var total2=addCommasandsign(total);

by:

var total2=addCommasandsign(total.toFixed(2));

This fixes the problem of zeros disappearing after the decimal point. If for example you had $1,133.00 + $1,900.00 you would see $3,033

With this fix you'll see the zeros after the decimal point => $3,033.00

You can see the live example here

******************** UPDATE 1 **********************

You can find a live example of the working code here


The following should work but didn't test it:

function addCommasandsign(nStr)
   {
nStr += '';
x = nStr.split('.');
x1 = x[0];
x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
    x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
return '$' + x1 + x2;
    }

//get html
var firstval=document.getElementById('firstAmount').innerHTML;
var secval=document.getElementById('secondAmount').innerHTML;
//replace $ and , by nothing
firstval=firstval.replace('$','');
firstval=firstval.replace(',','');
secval=firstval.replace('$','');
secval=firstval.replace(',','');
//add values
var total=firstval + secval;
//put , and $ back in place
var total2=addCommasandsign(total);
//insert in html
document.getElementById('totalAmount').innerHTML=total2;


To convert '$1,133.79' to a real number, you could do something like:

var tmp   = '$1,133.79'.replace(/^\$/,'').split(/[,.]/),
    value = tmp.length === 3
             ? parseFloat(tmp.slice(0,2).join('')+'.'+tmp.slice(tmp.length-1))
             : parseFloat(tmp.join(''));

Or use this:

var Currency = function(){
    function tryParse(val){
    var tmp  = val.match(/\d+[.,]\d+[.,]\d+|\d+[.,]\d+/g)[0].split(/[,.]/);
    if (tmp.length < 2 || tmp.length>3){
      throw 'invalid input value';
    }
    return tmp.length === 3
           ? Number(tmp.slice(0,2).join('')+'.'+tmp.slice(tmp.length-1))
           : Number(tmp.join(''));
    }
    return {parse: tryParse};
}();
//usage
Currency.parse('€ 30.000,23');               //=> 30000.23
Currency.parse('$30,000.23');                //=> 30000.23
Currency.parse('Pound Sterling £30,000.23'); //=> 30000.23
Currency.parse('30,000.23 (dollars)');       //=> 30000.23
Currency.parse('₯30.000,23');                //=> 30000.23
//etc.


You can try this (jsFiddle):

function add(x1, x2) {
    // e.g. x1 = "$1,133.79", x2 = "$1,900.00"
    x1 = x1.replace(/[$,]/g, "");
    x2 = x2.replace(/[$,]/g, "");
    var sum = (parseFloat(x1) + parseFloat(x2)).toFixed(2);
    var parts = sum.split(".");
    var len = parts[0].length;
    sum = "$";
    for (var i1 = 0, i2 = len % 3; i2 <= len; i1 = i2, i2 += 3) {
        sum += parts[0].slice(i1, i2);
        if (i2 < len) sum += ",";
    } 
    if (parts.length > 1) sum += "." + parts[1];
    return sum;
}

var sum = add("$1,133.79", "$1,900.00");  // == "$3,033.79"
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜