Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 (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.

like image 242
drmrbrewer Avatar asked Jul 22 '15 10:07

drmrbrewer


2 Answers

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.

like image 183
rholmes Avatar answered Nov 14 '22 08:11

rholmes


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:

  1. Number function does not perform "double-conversion" if the input is already a number (ref)
    • Parse float converts the input to a string then extracts the number (ref)
  2. Number function returns common sense values for most datatypes e.g. Number(true) yields 1
    • Parse float uses the string value of input so parseFloat(true) tries to parse number from "true" and yields NaN
  3. Number function fails when input string is an invalid number e.g. Number("123abc") yields NaN
    • Parse float tries to parse as much of a number as possible e.g. parseFloat("123abc") yields 123
like image 32
Salman A Avatar answered Nov 14 '22 09:11

Salman A