Home > Software design >  how to perform addition in Node Js?
how to perform addition in Node Js?

Time:09-10

This is my code

const calculator = (req, res) => {
    let option = req.body.option
    let num1 = req.body.num1
    let num2 = req.body.num2
    //console.log(num1   num2)

    if (option == ' ') {
        res.status(200).send({
            success: true,
            result: num1   num2
        })
    }
}

module.exports = { calculator }

I am trying to add num1 and num2, for eg num1 = 2 and num2 = 2 expected result should be 'result: 4'

but instead of result: 4 I am getting result: 22

CodePudding user response:

That's because num1 and num2 are strings. You propably get the values from and input field which always translates anything entered to a string.

Just do

 let num1 = parseInt(req.body.num1)
 let num2 = parseInt(req.body.num2)

and you're good to go.

CodePudding user response:

This is because both variable are 'string' when you get from request.

Use this as result

result: Number(num1)   Number(num2)

Ref: Number()

CodePudding user response:

Or shorter

            result:  num1    num2

as '2' for js engine is equivalent to Number('2')

  • Related