Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple JavaScript addition issues

I'm not so good with JS and for some reason when I try to add two fields together it joins them rather than adding the sum together.. this is the code I'm trying to use..

    function calculateTotal() {

        var postageVal = document.getElementById('postage').value; //$68.50
        var subtotalVal = document.getElementById('subtotal').value; //$378.00

        var postage = postageVal.substr(1); //68.50
        var subtotal = subtotalVal.substr(1); //378.00
        var totalVal = postage+subtotal;

        alert(postage);
        alert(subtotal);
        alert(totalVal);

    };

The totalVal is echoing/alerting out 68.50378.00 rather than adding them together.. could someone please tell me where I've gone wrong? :( The idea is to update the "total" textfield with totalVal, but I haven't gotten that far yet!

like image 578
SoulieBaby Avatar asked Jun 05 '09 11:06

SoulieBaby


People also ask

Why addition is not working in JS?

1 Answer. This happens when one or both of the variables is String which results in string concatenation. The arithmetic operators like / * - performs a toNumber conversion on the string(s). In order to convert a string to a number : use the unary + operator.

How do you do addition in JavaScript?

Add numbers in JavaScript by placing a plus sign between them. You can also use the following syntax to perform addition: var x+=y; The "+=" operator tells JavaScript to add the variable on the right side of the operator to the variable on the left.


1 Answers

You need to convert your values to a float before adding them:

var totalVal = parseFloat(postage) + parseFloat(subtotal);

EDIT: Here's a complete example that includes a check for NaN:

function calculateTotal() {

    var postageVal = document.getElementById('postage').value; //$68.50
    var subtotalVal = document.getElementById('subtotal').value; //$378.00

    var postage = parseFloat(postageVal.substr(1)); //68.50
    var subtotal = parseFloat(subtotalVal.substr(1)); //378.00
    var postageAsFloat = isNaN(postage) ? 0.0 : postage;
    var subtotalAsFloat = isNaN(subtotal) ? 0.0 : subtotal;
    var totalVal = postageAsFloat + subtotalAsFloat;

    alert(postage);
    alert(subtotal);
    alert(totalVal);

};
like image 105
Ray Vernagus Avatar answered Sep 30 '22 16:09

Ray Vernagus