Silly JavaScript question

I realize this isn't strictly a Node-RED question, but it came up in designing a validation function for a custom node. I want to test whether a text input represents an integer. I get these results:

let v = '3'
node.warn(Number.isInteger(v))                      // false
node.warn(Number.isInteger(Number.parseFloat(v)))   // true

Is there a less silly-looking way to write the third line?

[EDIT] OK, I just realized I can get away with Number.isInteger(Number(v)). Still, for a language that is so careless with type conversion, I expected less...

Number(v) % 1 === 0 should also work, you could omit the Number() as JS will force a number when using modulus, but you would need to suppress the editor error.

Nice. Suggests Number.isInteger(-v).

Actually, I want a positive integer, so there is a bit more work to do.

Number.isInteger(+v)

Number.isInteger(+v) will not verify the string v is a positive integer

image

That's right. So far, the least ugly is

+v > 0 && Number.isInteger(+v)

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