Home  >  Q&A  >  body text

What are the ways to convert strings to integers in JavaScript and which one is the fastest?

What are the methods? Which method is fastest!
Number()
parseInt()

三叔三叔2633 days ago958

reply all(8)I'll reply

  • 伊谢尔伦

    伊谢尔伦2017-07-05 10:43:53

    (unofficial) test results, see for yourself

    Number()

    parseInt()

    Math.floor()

    Math.round()

    Math.ceil()

    |0

    ^0

    -0

    Math.floor+

    -Math.floor-

    --split[0]

    +split[0]

    reply
    0
  • 大家讲道理

    大家讲道理2017-07-05 10:43:53

    +'123'

    reply
    0
  • 仅有的幸福

    仅有的幸福2017-07-05 10:43:53

    Math.floor(+'123.123');
    
    -Math.floor(-'123.123')
    
    -(-'123.213'.split('.')[0]);
    
    +'123.213'.split('.')[0]

    There are many conversion methods, but they are all small tricks of using operators for implicit conversion.

    In addition to priority and associativity, please also note that different operands will affect the implicit conversion of operators.

    reply
    0
  • 巴扎黑

    巴扎黑2017-07-05 10:43:53

    There are also these methods,
    '3.1425' | 0
    '7.86'^0
    '123'-0

    I feel like the methods specifically used for conversion are faster, like parseInt and Number you mentioned. I haven’t tried it personally

    reply
    0
  • 三叔

    三叔2017-07-05 10:43:53

    var a = 1.123445;
    a >> 0;

    reply
    0
  • 三叔

    三叔2017-07-05 10:43:53

    String inString = ""; // The inString variable is used to store the value from the input

    Void setup () {
      // Open serial port with baudrate 9600
      Serial.begin (9600);
      While (! Serial) {
        ; // wait Serial port is turned on (just with Arduino Leonardo circuit)
      }

      // Send a message that the setup function has finished
      Serial.println (" n nChanges compared to:");
      Serial.println ();
    }

    Void loop () {
      // Read the value from Serial
      While (Serial.available ()> 0) {
        Int inChar = Serial.read ();
        If (isDigit (inChar)) {// Check function NUMBER is a digital character
          // and add strings. Otherwise you will add an integer to it: P
          InString + = (char) inChar;
        }
        // If inChar is a newline character. I print the results
        If (inChar == ' n') {// One character uses '(single quote) and one string to use' (double quotes)
          Serial.print ("value:");
          Serial.println (inString.toInt ());
          Serial.print ("string:");
          Serial.println (inString);
          // delete the value of the inString variable
          InString = "";
        }
      }
    }
    photo editor

    reply
    0
  • 滿天的星座

    滿天的星座2017-07-05 10:43:53

    Also~~'123.45'

    reply
    0
  • 滿天的星座

    滿天的星座2017-07-05 10:43:53

    var a = '1'

    var b = a * 1

    b is number

    reply
    0
  • Cancelreply