drmrbrewer
drmrbrewer

Reputation: 13029

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.

Upvotes: 7

Views: 3226

Answers (6)

Kaspar Fenner
Kaspar Fenner

Reputation: 161

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.

Upvotes: 1

Salman Arshad
Salman Arshad

Reputation: 272246

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

Upvotes: 1

cнŝdk
cнŝdk

Reputation: 32145

Wether it's a float or a String using parseFloat() is much safer to avoid all kind of errors.

As you said it will always work, but if you enforce it to be a float you will avoid getting any Exception.

For Example:

Both parseFloat('10.2', 10) and parseFloat(10.2, 10) will work perfectly and will give you the same result which is 10.2.

Upvotes: 0

axelduch
axelduch

Reputation: 10849

Nope there is no problem with passing a number to it

MDN says as long as it can be converted to a number, nothing breaking should happen.

If the first character cannot be converted to a number, parseFloat returns NaN.

As an alternative, you could use the unary operator + which does basically the same thing as parseFloat and also returns NaN if it didn't work.

For instance:

var myFloat = +('10.5');
var myOtherFloat = parseFloat('10.5', 10);
var alreadyAFloat = parseFloat(10.5, 10);

console.log(myFloat === myOtherFloat && myOtherFloat === alreadyAFloat); // true

Upvotes: 0

rholmes
rholmes

Reputation: 4174

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.

Upvotes: 1

Canvas
Canvas

Reputation: 5897

Personally I can't see this being a problem what so ever, to be honest I would always use the parsefloat() for one reason, and that is safety. You can never be to sure what may happen, so always predict the worse :D

Upvotes: -1

Related Questions