Action Script string to number

30,276

Solution 1

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.

Solution 2

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.

Share:
30,276
sameer jain
Author by

sameer jain

Updated on July 09, 2022

Comments

  • sameer jain
    sameer jain almost 2 years

    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?

  • sameer jain
    sameer jain over 12 years
    The statement was input by user so I can not remove the quotation. Any other way to solve that?
  • weltraumpirat
    weltraumpirat over 12 years
    Your explanation is correct concerning numbers, but a) Number () is not a constructor, but a top level conversion function help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/‌​… , and b) it is safer and more accurate to use parseFloat() or parseInt() to convert strings to numerical values (parses the string until the first non-numerical character, and always returns NaN, if the string can't be converted - check the table for Number()'s possible return values to see what I mean).
  • Swati Singh
    Swati Singh over 12 years
    @weltraumpirat: thanx for correcting me. i have modified my answer as Number() is not a constructor.
  • crooksy88
    crooksy88 over 12 years
    Is your input always the same format? i.e. a fraction? Is so you could parse the string, getting the characters before the / and the ones after the / and then perform your calculation on those substrings. e.g. var str:String = "1"; var str2:String = "2"; trace(Number(str) / Number(str2)); //output 0.5