1

In the below code, a != b when compared with ==. My initial thought is that JavaScript would use the same conversion for parseFloat as it would with ==. Can anyone explain what actually happens as I'm a little confused by this. b = 129 when parsed, so it appears parseFloat will parse up to the first non-numeric character.

var a = '129t3.98';
var b;

b = parseFloat(a);

Here is the sample script fiddle.

I was looking to put together a very simple isNumeric() function using this, but I want to understand it first.

Yatrix
  • 13,361
  • 16
  • 48
  • 78

2 Answers2

1

The parseFloat function, as you've noticed, will parse up to the first character that satisfies the grammar for numeric literals. From the spec:

Let numberString be the longest prefix of trimmedString, which might be trimmedString itself, that satisfies the syntax of a StrDecimalLiteral.

However, the abstract equality comparison algorithm (that's what == does) does not follow the same rules:

If Type(x) is String and Type(y) is Number, return the result of the comparison ToNumber(x) == y

And here's what the internal ToNumber operation has to say:

If the grammar cannot interpret the String as an expansion of StringNumericLiteral, then the result of ToNumber is NaN.

So when you attempt to compare your string with the number resulting from parsing it, you're actually comparing the number NaN.

James Allardice
  • 164,175
  • 21
  • 332
  • 312
0

When you are giving a=b, then the value of b goes to a, without any conversion.

When you are assigning the value as a=parseFloat(b), if b is of type string then a will be of type int.

but if a= b is assigned , then a & b are both same types.

if,2->int, '2' -> string 
2=='2'   (true)
2 === '2' (false)

by observing above conversions u can handler ur code accordingly.

Yatrix
  • 13,361
  • 16
  • 48
  • 78
Avenger
  • 205
  • 2
  • 10