Science
Copyright © 2024 Jiri Kriz, www.nosco.ch
Snippet so7430295
Back to Overview

Add amounts and put in element


<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">    
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;
}
</script>
</head>
<body>   
<script type="text/javascript">
    var sum = add("$1,133.79", "$1,900.00");
    document.write("Sum = " + sum);
</script>    
</body>
</html>