分享

Converting Strings to Numbers

 昵称9154740 2012-03-21

Question: How do I convert strings to numbers in JavaScript?

Answer: To convert a string to a number, use the JavaScript functions

  • parseFloat (for conversion to a floating-point number) or
  • parseInt (for string-to-integer conversion).

    parseFloat syntax:   parseFloat(string)

    How it works:
    The argument of parseFloat must be a string or a string expression. The result of parseFloat is the number whose decimal representation was contained in that string (or the number found in the beginning of the string). If the string argument cannot be parsed as a decimal number, the result will be NaN (not-a-number value).

    Examples (comments in each line give the conversion results):

    parseFloat('1.45kg')  // 1.45
    parseFloat('77.3')    // 77.3
    parseFloat('077.3')   // 77.3
    parseFloat('0x77.3')  // 0
    parseFloat('.3')      // 0.3
    parseFloat('0.1e6')   // 100000
    

    parseInt syntax:   parseInt( string [, base] )

    How it works:
    The first argument of parseInt must be a string or a string expression. The result returned by parseInt is an integer whose representation was contained in the string (or the integer found in the beginning of the string). The second argument base, if present, specifies the base (radix) of the number whose string representation is contained in the string. The base argument can be any integer from 2 to 36.

    If there is only one argument, the number base is detected according to the general JavaScript syntax for numbers. Strings that begin with 0x or -0x are parsed as hexadecimals; strings that begin with 0 or -0 are parsed as octal numbers. All other strings are parsed as decimal numbers.

    If the string argument cannot be parsed as an integer, the result will be NaN (or 0 in very old browsers such as Internet Explorer 3.0).

    Examples (comments in each line give the conversion results):

    parseInt('123.45')  // 123
    parseInt('77')      // 77
    parseInt('077',10)  // 77
    parseInt('77',8)    // 63  (= 7 + 7*8)
    parseInt('077')     // 63  (= 7 + 7*8)
    parseInt('77',16)   // 119 (= 7 + 7*16)
    parseInt('0x77')    // 119 (= 7 + 7*16)
    parseInt('099')     // 0 (9 is not an octal digit)
    parseInt('99',8)    // NaN (0 in very old browsers e.g. IE3)
    parseInt('0.1e6')   // 0
    parseInt('ZZ',36)   // 1295 (= 35 + 35*36)
    
    • 本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
      转藏 分享 献花(0

      0条评论

      发表

      请遵守用户 评论公约

      类似文章 更多