Search code examples
javascriptnode.jspostgresqlrestparseint

Number() when used on a string returns Nan


Here's the code I'm working on:

app.put("/transaction/:value/:id1/:id2", async(req,res) => {
    try {
        const {value,id1,id2} = req.params;

        const bal1 = await pool.query("Select balance from balance where id=$1",[id1]);
        const bal2 = await pool.query("Select balance from balance where id=$1",[id2]);

        const ball1 = JSON.stringify(bal1.rows[0].balance);
        const ball2 = JSON.stringify(bal2.rows[0].balance);
        const convball1 = Number(ball1);
        
        console.log(convball1);

This is a PERN project I'm trying working on and I need the convball1 value as int to further test conditions but I am not able to use it as int.

When the bal1 value was retrieved from the database, it came out as like this: [{"balance":"50"}] which is why the sanitizing at ball1. But the value at ball1 shows up as "50".

Need ball1 has an integer

Update: I did as mentioned used parseInt() instead of Number(), but I got the same error. So, I checked the MDN web docs for the parseInt() funtion and they mention using another argument called radix.

So, a radix of 10 will convert decimal numbers to int format, but I'm not sure I'm doing it right. Getting the same error


Solution

  • You mentioned you get [{"balance":"50"}] as your output;

    When I do [{"balance":"50"}][0].balance I will get "50" and Number("50") will give me 50.

    You are doing JSON.stringify([{"balance":"50"}][0].balance) will result in ""50"" and Number(""50"") will be Nan

    Avoid JSON.stringify and you would be good.