Convert a string to an integer use parseInt or Number
What should we use to convert a string to an integer? parseInt or Number?
parseInt and Number are semantically different, the Number constructor called as a function perform type conversion, but parseInt perform parseing.
// type conversion
Number("20px"); // NaN
Number("2e1"); // 20, exponential notation
// parsing:
parseInt("20px"); // 20
parseInt("10100", 2); // 20
parseInt("2e1"); // 2
Keep in mind that bothparseInt and Number ignore the leading zero on the string, it will parse the number in decimal base, this is the standard on ECMAScript 5. In addition, parseInt will ignore trailing characters that don't correspond with any digit of the currently used base.
Number("010"); // 10
parseInt("0010"); // 10, decimal
parseInt("0010", 10); // 10, decimal radix used
parseInt("0010e"); // 10, ignore trailing char that don't correspond with currently used base
Both parseInt and Number can handle numbers in hexadecimal notation:
Number("0xF"); // 15
parseInt("0xF"); //15
Latest Post
- Dependency injection
- Directives and Pipes
- Data binding
- HTTP Get vs. Post
- Node.js is everywhere
- MongoDB root user
- Combine JavaScript and CSS
- Inline Small JavaScript and CSS
- Minify JavaScript and CSS
- Defer Parsing of JavaScript
- Prefer Async Script Loading
- Components, Bootstrap and DOM
- What is HEAD in git?
- Show the changes in Git.
- What is AngularJS 2?
- Confidence Interval for a Population Mean
- Accuracy vs. Precision
- Sampling Distribution
- Working with the Normal Distribution
- Standardized score - Z score
- Percentile
- Evaluating the Normal Distribution
- What is Nodejs? Advantages and disadvantage?
- How do I debug Nodejs applications?
- Sync directory search using fs.readdirSync