Passing a number to parseFloat() instead of string
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 (eg "temp": "10.2"
), while for other sources the json element will already be a float (eg "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 (ie, 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 NaN Number("123abc")
yields NaN parseFloat("123abc")
yields 123 If you are sure the value is always a valid number, you should use Number(stringOrNumber)
.
If you need some additional safety using parseFloat()
you could also write your own function which is also performance optimized:
function toFloat(value) {
return typeof value === 'number' ? value : parseFloat(value);
}
I also created a jsPerf test case that shows the performance is >30% better than the plain parseFloat()
for a 1:1 ratio between strings and numbers as input values.
上一篇: WPF中的“无限”面板