H M Mohidul Islam
H M Mohidul Islam

Reputation: 87

Addition not working correctly in ExpressJs, Where subtraction is working correctly

I am doing a NodeJs Project. I am facing this problem.Subtraction is working correctly But addition is creating the problem.................

var previous_stock=results[0]['remain_stock']; //suppose value is 123
    var products_qty=request.body.products_qty;  //suppose valut is 7

    var update_data={
        remain_stock:previous_stock-products_qty, //output is 116
    }
    var update_data2={
        remain_stock:previous_stock+products_qty, //output is 1237
    }

How to solve that problem??

Upvotes: 2

Views: 186

Answers (1)

Nicky McCurdy
Nicky McCurdy

Reputation: 19554

When used on a String, the + operator concatenates, even if the String only consists of digits. Assuming all your string values are base 10, wrap them in parseInt(string, 10). Note that you should also do this to products_qty if it's a String.

var previous_stock = results[0].remain_stock
var products_qty = request.body.products_qty

var update_data = {
  remain_stock: parseInt(previous_stock, 10) - products_qty
}

var update_data2 = {
  remain_stock: parseInt(previous_stock, 10) + products_qty
}

Upvotes: 2

Related Questions