TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

<< Back to JAVASCRIPT

JavaScript parseInt Examples

Convert strings to ints with the parseInt function. Use Number and parseFloat.
ParseInt. A program sometimes has a string but needs an int. For example in numerical operations, ints can be used but strings cannot be.
Conversion syntax. In JavaScript we can convert a string to an int with parseInt, a built-in method. Another option is with plus (to implicitly convert to an int).
First example. Here we have a string with 5 digits in it. To explore numeric conversions in JavaScript, we surround our parsing statements in a loop.

Part A: We loop over the digits in our string with a for-loop and convert each one to a number.

Part B: We use parseInt, a plus, and the Number constructor. Each string is converted in 3 different ways.

Strings

Sum: We sum up all the numbers to show that they are valid digits and get the value 45.

JavaScript program that gets integers from string var codes = "12345"; var sum = 0; // Part A: loop over chars and convert them to ints. for (var i = 0; i < codes.length; i++) { // Part B: apply numeric conversion. var test1 = parseInt(codes[i]); var test2 = +codes[i]; var test3 = Number(codes[i]); // Write our ints. console.log("INT: " + test1); console.log("INT: " + test2); console.log("INT: " + test3); // Sum the total. sum += test1 + test2 + test3; } // Write the sum. console.log("SUM: " + sum); Output INT: 1 INT: 1 INT: 1 INT: 2 INT: 2 INT: 2 INT: 3 INT: 3 INT: 3 INT: 4 INT: 4 INT: 4 INT: 5 INT: 5 INT: 5 SUM: 45
ParseFloat. Suppose we have a number with a fractional part like 1.5. This is a floating-point number. We need to use the parseFloat method to retain the fractional part.

Here: We use parseInt, which discards everything after the decimal place, and parseFloat.

JavaScript program that uses parseFloat var test = "100.534"; var resultInt = parseInt(test); console.log("PARSEINT: " + resultInt); var resultFloat = parseFloat(test); console.log("PARSEFLOAT: " + resultFloat) Output PARSEINT: 100 PARSEFLOAT: 100.534
IsNaN. Sometimes a string cannot be parsed. It may contain a word or other text. Here the parseInt method returns NaN, a special value in JavaScript.

IsNan: We can use the isNaN built-in method to test to see if nothing was parsed by parseInt.

JavaScript program that uses parseInt, isNaN // This string cannot be parsed. var test = "abc"; var result = parseInt(test); console.log("PARSEINT: " + result); // We can detect not a number with isNaN. if (isNaN(result)) { console.log("ISNAN"); } Output PARSEINT: NaN ISNAN
Benchmark, parseInt. Which method should we use to convert strings to ints? Some options, like parseInt and Number, are available. We tested them in a loop with a switch.

Version 1: This version of the code uses the plus operator to convert a digit character into an integer.

Version 2: This version uses the parseInt method, which handles more cases of numeric conversion.

Version 3: Here we use the Number() function to get an integer from a string. We use each integer in a switch.

Result: In a Chromium version from 2019 I found that using Number() is the fastest approach to converting a string to an int.

And: Using parseInt took about twice the time. So avoiding parseInt unless needed is a good approach.

JavaScript program that benchmarks int parsing var c = 0; var codes = "123456"; var x1 = performance.now(); // Version 1: use plus. for (var i = 0; i < 10000000; i++) { for (var z = 0; z < codes.length; z++) { switch (+codes[z]) { case 1: c++; break; case 2: c--; break; case 3: c += 2; break; default: c = 0; break; } } } var x2 = performance.now(); // Version 2: use parseInt. for (var i = 0; i < 10000000; i++) { for (var z = 0; z < codes.length; z++) { switch (parseInt(codes[z])) { case 1: c++; break; case 2: c--; break; case 3: c += 2; break; default: c = 0; break; } } } var x3 = performance.now(); // Version 3: use Number. for (var i = 0; i < 10000000; i++) { for (var z = 0; z < codes.length; z++) { switch (Number(codes[z])) { case 1: c++; break; case 2: c--; break; case 3: c += 2; break; default: c = 0; break; } } } var x4 = performance.now(); // Results. console.log("TIME 1: " + (x2 - x1)); console.log("TIME 2: " + (x3 - x2)); console.log("TIME 3: " + (x4 - x3)); Output TIME 1 (2019): 276.049 Plus TIME 2: 332.764 parseInt TIME 3: 270.944 Number
Notes, parseInt. We have found that using a plus to convert a string to an int is a fast solution. But the fastest approach is to do no conversion at all.

Tip: With some JavaScript changes to how data is stored, you can often have the numbers in their native format already.

A summary. When necessary, a plus sign provides fast string to int conversions in Chromium. Other modern browsers seem to have similar benefits here.
© TheDeveloperBlog.com
The Dev Codes

Related Links:


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf