Bob Boby
Bob Boby

Reputation: 193

I can't use parseInt on JSON data from redis?

So I have been having issues with redis. I've only recently started learning how to use it but basically, I know how to send JSON, and get JSON. Which is all I need. Now the issue is that when I try and parseInt the json data I get nothing. It's just 0. When I used fs with a json file. I didn't even need to parseInt, but with redis I can't do anything with the JSON I receive. So I want to ask. How can I send data, call for it, then turn it into numbers I can use to make calculations. I should also mention I have tried sending int values in keys but that also didn't work. I will leave some snippets of code that I used to test redis.

function logvalues() {
    redisClient.set("industrial", redisdatabase.industrial, (err) => {
        if (err) {
            console.log(err)
        } else {
            console.log(`New average values logged, industrial: ${redisdatabase.industrial}`);
        }
    });
    redisClient.set("milspec", JSON.stringify(redisdatabase), (err) => {
        if (err) {
            console.log(err)
        } else {
            console.log(`New average values logged, milspec: ${redisdatabase.milspec}`);
            redisClient.get("milspec", (err, reply) => {
                if (err) {
                    console.log(err)
                } else {
                    console.log(reply);
                    reply = JSON.parse(reply);
                    var milspecvalue = reply.milspec.valueOf();
                    console.log(milspecvalue)
                }
            });
        }
    });
}

also, here are some logs:

2020-01-13T23:20:45.606166+00:00 app[web.1]: Average value = 0.09666666666666668
2020-01-13T23:20:45.607392+00:00 app[web.1]: New average values logged, industrial: 0.07
2020-01-13T23:20:45.607818+00:00 app[web.1]: New average values logged, milspec: 0.09666666666666668
2020-01-13T23:20:45.608896+00:00 app[web.1]: 0.09666666666666668
2020-01-13T23:20:45.608979+00:00 app[web.1]: No parse int: 0.096666666666666681
2020-01-13T23:20:45.609050+00:00 app[web.1]: ParseInt value: 0
2020-01-13T23:20:45.609102+00:00 app[web.1]: ParseInt + 1: 1

Upvotes: 2

Views: 485

Answers (1)

Luis Felipe Zaguini
Luis Felipe Zaguini

Reputation: 66

If you use parseInt, it will truncate the integer without rounding it, so it essentially converts to 0.

For rounding, you can use Math.floor, Math.ceil or Math.round, which rounds to the closest of them.

If precision is important, you can use the .toFixed method on numbers. Example:

(0.12311).toFixed(2) // yields "0.12"

But it will convert to string. So to keep precision while still dealing with numbers, use parseFloat. Example:

parseFloat((0.12311).toFixed(2)) // 0.12, this time as a number you can operate on

Upvotes: 3

Related Questions