1

In HTML you can use <input type="number"> which can be float or int, depending on the "step" parameter.

If I read this value via JavaScript I get always a string.

Is there already a handy method which does this iffing and elseing to extract the matching javascript data type?

This question is not about submitting the form via http GET/POST. It is about reading the input elements via JS.

guettli
  • 25,042
  • 81
  • 346
  • 663
  • 5
    *which can be float or int* There is no difference in Javascript. Just use `Number` – CertainPerformance Oct 11 '19 at 12:11
  • JavaScript does not distinguish between integers and floats. They are all Numbers—and if you're sending an HTTP request with a query string, you should convert it to a Number server side (if you're using node or similar) – Andrew Li Oct 11 '19 at 12:11
  • 1
    See if this helps -> https://stackoverflow.com/questions/3885817/how-do-i-check-that-a-number-is-float-or-integer – Vishal Kumar Oct 11 '19 at 12:12
  • Text fields are strings, JS only has floating point. – Dave Newton Oct 11 '19 at 12:20

2 Answers2

0

You can use the built in function Number.parseInt(). You can then the use Number.isNaN(parsed) to check if it could be parsed and prevent errors.

Check this out for more information.

Josef
  • 304
  • 2
  • 14
  • That won't differentiate between whole and decimal numbers, which is what the OP is asking about. – Dave Newton Oct 11 '19 at 12:21
  • I recommend expanding your answer to address `parseFloat` in the context of this question. It will still convert strings that don't have decimals just fine, but it won't truncate at the decimal place if it's present. Since the OP specified that float is a possible, there may be a case for either parsing static method. Where decimals are valid, parseFloat handles both "int" and "float" strings equally fine in JS. – Mic Oct 11 '19 at 12:24
  • [Here](https://stackoverflow.com/questions/3885817/how-do-i-check-that-a-number-is-float-or-integer/20779354#20779354) is a question where it is discussed how to check the number type. – Josef Oct 11 '19 at 12:27
  • I know that i can use `parseInt()`. I wanted to know: Is there already a handy method which does this iffing and elseing to extract the matching javascript data type? – guettli Oct 21 '19 at 10:27
0

You can do Type casting...

var x="10"
alert("first it is string   "+typeof(x))

alert("After doing type casting  "+typeof(Number(x)))
siddesh
  • 41
  • 3