Why am I getting the wrong *type* of data in this message?

Sorry @Colin but that doesn't help me.

think and probably aren't very reassuring to me.

When I look up parseInt() it tells me it returns an INTEGER.

Where does the converting to a string come into the mechanics?

The original payload (message part, sorry.) is already a number.... Ok, not an integer, but a number, so the maths I do should work.

What does that link say about the type of the value that it is parsing? It says
"The JavaScript number parseInt() method parses a string argument"
so it expects a string.
The MDN site is a better set of docs for javascript and it has this clarification in the Description:
The parseInt function converts its first argument to a string, parses that string, then returns an integer or NaN.

Yes it does, I was just pointing out that round() is more efficient than parseInt() as it converts the number to the nearest integer without formatting it as a string and then parsing the string to turn it back to a number again.

1 Like

Yes, that is exactly what you should do. Or better still, x10 and then use parseInt(mynumber, 10) to get the integer since that returns a number and not a string (it can be fed with a number or a string representation of a number so parseInt("1h", 10) will return the number 1.


Oops, sorry Colin, didn't see your answer along the same lines.

1 Like

Ok, thanks.

So if the original value is already a number, then parseInt is not the right way to do it.
But round is better.

Also thanks for the MDN site link.
I may have to bookmark that.
(Though as with all the other bookmarks: remembering I have it is a whole other story.)

MDN and W3Schools are usually the top sites when I search for a javascript function. W3Schools can be better if you are looking for simple examples, MDN is more detailed.

Thanks.

I really need to learn all these tricks, but I shall say I do not want to get ahead of myself either.

I write my code the long way so I can see it better a few days/weeks later and still (I hope) understand what it does.

No offense to anyone - but optimising code to one line can be handy but also confusing if you don't really understand what is happening.

So to check:
parseInt("1h", 10)
Confusing - and I am not sure you meant it to be.
But I have a payload with "1h" in it from the openweather node.
The line:
let rain_now = parseInt(msg.data.rain["1h"]*10);

Could you explain it another way?
Please.

And not forgetting that ChatGPT can be really helpful when you get stuck. Though it doesn't always give you the best answer and indeed, not always the correct one, but it will give you enough clues to make progress and for fairly straight-forward things and even most really complex ones, it will give good answers.

In my browser, I have a search shortcut called mdn so that I can type mdn parseInt and get straight to the page.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.