Script action line to number

I have a problem with the following statement

trace(Number("1/2")) //output NaN 

but

 trace(Number("1.2")) //output 1.2 

So, I'm a little confused, why doesn't the first statement give the correct result?

+4
source share
3 answers

Probably, this value will already be a number, not a calculation. Try to parse this line: "1+2" . This will most likely also result in NaN.


Edit: I ran 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.

+12
source

You can convert strings of numeric characters to actual Number data using Number (). The way it works is that you pass the String value to Number (), and in turn, this will create the version of the String number that was passed to it.

  trace(Number("1")/Number("2")); // Output 0.5 

NaN is the result because you are trying to convert String data to be used as number data.

You need to follow this up because the "/" operator is not a number. You can only multiply or divide numbers, not strings. So, during the process of dividing String data, we implicitly force the values ​​to change to numerical data. We cannot do this. We must first convert the String data to numeric data, and then perform an arithmetic operation.

+1
source

By enclosing the value in the quotation parks, you make it an explicit string. He likes to ask what the numerical meaning of the word "this" is.

Not sure if this helps, but remove quotes and make sense.

 trace(Number(1/2)); //output 0.5 
-one
source

Source: https://habr.com/ru/post/1393317/


All Articles