I have a problem with following statement
trace(Number("1/2")) //output NaN
but
trace(Number("1.2")) //output 1.2
So, I am bit confused as why the first statement doesn't gives correct result?
I have a problem with following statement
trace(Number("1/2")) //output NaN
but
trace(Number("1.2")) //output 1.2
So, I am bit confused as why the first statement doesn't gives correct result?
It probably expects the value to be a number already, not a calculation. Try to parse this string: "1+2"
. It'll most likely result in NaN as well.
Edit: I've run a test
Number("1.2") = 1.2
Number("1+2") = NaN
Number("1/2") = NaN
So, as I said, the Number()
constructor expects a number, not a calculation.
You can convert strings that are made up of numerical characters into actual Number data using the Number(). The way it works is that you pass the String value to the Number(), and in turn, this will create a Number version of the String that was passed to it.
trace(Number("1")/Number("2")); // Output 0.5
NaN is the output because you are trying to convert the String data to be used as Number data.
You have to trace like this because "/" operator is not a number. You can only multiply or divide numbers, NOT strings. So in the act of trying to divide String data, we are implicitly coercing the values to change into Number data. We can't do that. We should explicitly convert the String data to Number data first, and then perform the arithmetic operation.
By enclosing the value inside quotation parks you are making it an explicit string. It's like asking what is the number value of the word "this".
Not sure if this helps but remove the quotation marks and it makes sense.
trace(Number(1/2)); //output 0.5