In my code, the value of a particular var can originate from any one of a number of different json sources. For some of those sources, the json element concerned will be a string (e.g. "temp": "10.2"
), while for other sources the json element will already be a float (e.g. "temp": 10.2
).
Does it do any harm (is anything likely to break) if I just pass the json element (from whatever source) through a parseFloat()
, even if it's already a float? It seems to work; I'm just thinking about good/bad practice and possible breakage in future or on a different platform.
Thanks.
You should be able to call parseFloat() on a float or a string without any problems. If it is a float already, it's converted to a string first, and then to a float again, so it's a little less efficient, but it shouldn't matter too much.
You should still check the result for NaN, in case there's something unexpected in the data.
The most appropriate method to convert any datatype to a number is to use the Number
function:
In a non-constructor context (i.e., without the
new
operator),Number
can be used to perform a type conversion.
Number("1234") // 1234
Number(1234) // 1234
This method differs from parseFloat
in these ways at least:
Number(true)
yields 1
parseFloat(true)
tries to parse number from "true"
and yields NaNNumber("123abc")
yields NaN
parseFloat("123abc")
yields 123If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With