惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Spread Privacy
Spread Privacy
K
Kaspersky official blog
Application and Cybersecurity Blog
Application and Cybersecurity Blog
Forbes - Security
Forbes - Security
Hacker News - Newest:
Hacker News - Newest: "LLM"
The Last Watchdog
The Last Watchdog
SecWiki News
SecWiki News
Attack and Defense Labs
Attack and Defense Labs
Google DeepMind News
Google DeepMind News
Security Archives - TechRepublic
Security Archives - TechRepublic
S
Secure Thoughts
WordPress大学
WordPress大学
Microsoft Security Blog
Microsoft Security Blog
P
Proofpoint News Feed
云风的 BLOG
云风的 BLOG
V
Visual Studio Blog
Security Latest
Security Latest
TaoSecurity Blog
TaoSecurity Blog
Cyberwarzone
Cyberwarzone
S
SegmentFault 最新的问题
Cloudbric
Cloudbric
aimingoo的专栏
aimingoo的专栏
S
Schneier on Security
N
Netflix TechBlog - Medium
MyScale Blog
MyScale Blog
T
The Blog of Author Tim Ferriss
H
Hacker News: Front Page
C
Cybersecurity and Infrastructure Security Agency CISA
小众软件
小众软件
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
AWS News Blog
AWS News Blog
AI
AI
G
GRAHAM CLULEY
IT之家
IT之家
P
Privacy & Cybersecurity Law Blog
L
Lohrmann on Cybersecurity
Last Week in AI
Last Week in AI
D
Docker
Recent Announcements
Recent Announcements
O
OpenAI News
T
Threat Research - Cisco Blogs
GbyAI
GbyAI
S
Security @ Cisco Blogs
T
Troy Hunt's Blog
C
Check Point Blog
博客园 - 三生石上(FineUI控件)
A
About on SuperTechFans
The Cloudflare Blog
阮一峰的网络日志
阮一峰的网络日志
N
News and Events Feed by Topic

Dmitri Pavlutin Blog

Pure Functions in JavaScript: A Beginner's Guide Record Type in TypeScript: A Quick Intro How to Write Comments in React: The Good, the Bad and the Ugly 4 Ways to Create an Enum in JavaScript React forwardRef(): How to Pass Refs to Child Components TypeScript Function Types: A Beginner's Guide How to Use v-model to Access Input Values in Vue Mastering Vue refs: From Zero to Hero Environment Variables in JavaScript: process.env 5 Must-Know Differences Between ref() and reactive() in Vue How to Destructure Props in Vue (Composition API) Triangulation in Test-Driven Development How to Use nextTick() in Vue Programming to Interface Vs to Implementation A Smarter JavaScript Mapper: array.flatMap() Array Grouping in JavaScript: Object.groupBy() How to Access ES Module Metadata using import.meta JSON Modules in JavaScript How to Trim Strings in JavaScript TypeScript Function Overloading How to Debounce and Throttle Callbacks in Vue How to Show/Hide Elements in Vue Sparse vs Dense Arrays in JavaScript How to Fill an Array with Initial Values in JavaScript Covariance and Contravariance in TypeScript What are Higher-Order Functions in JavaScript? How to Use TypeScript with React Components Index Signatures in TypeScript How to Use React useReducer() Hook unknown vs any in TypeScript A Guide to React Context and useContext() Hook How to Use Promise.any() 2 Ways to Remove a Property from an Object in JavaScript 'return await promise' vs 'return promise' in JavaScript How to Use Promise.allSettled() How to Use fetch() with JSON JavaScript Promises: then(f,f) vs then(f).catch(f) What is a Promise in JavaScript? How to Use Promise.all() A Simple Guide to Component Props in React Don't Stop Me Now: How to Use React useTransition() hook A Simple Explanation of JavaScript Variables: const, let, var ES Modules Dynamic Import How to Memoize with React.useMemo() How to Cleanup Async Effects in React Why Math.max() Without Arguments Returns -Infinity How to Debounce and Throttle Callbacks in React Don't Confuse Function Expressions and Function Declarations in JavaScript How to Use ES Modules in Node.js How to Use Array Reduce Method in JavaScript 3 Ways to Merge Arrays in JavaScript A Guide to Jotai: the Minimalist React State Management Library The Difference Between Values and References in JavaScript How to Implement a Queue in JavaScript A Helpful Algorithm to Determine "this" value in JavaScript React useRef() Hook Explained in 3 Steps 7 Interview Questions on "this" keyword in JavaScript. Can You Answer Them? How to Greatly Enhance fetch() with the Decorator Pattern 7 Interview Questions on JavaScript Closures. Can You Answer Them? What's a Method in JavaScript? array.sort() Does Not Simply Sort Numbers in JavaScript How to Solve the Infinite Loop of React.useEffect() The New Array Method You'll Enjoy: array.at(index) What's the Difference between DOM Node and Element? Why Promises Are Faster Than setTimeout()? Everything About Callback Functions in JavaScript How React Updates State 5 Mistakes to Avoid When Using React Hooks 5 Best Practices to Write Quality JavaScript Variables Type checking in JavaScript: typeof and instanceof operators 3 Ways to Check if a Variable is Defined in JavaScript React Forms Tutorial: Access Input Values, Validate, Submit Forms Prototypal Inheritance in JavaScript How to Timeout a fetch() Request How to Learn JavaScript If You're a Beginner A Simple Explanation of React.useEffect() A Simple Explanation of JavaScript Iterators How to Use React Controlled Inputs Everything about null in JavaScript How to Use Fetch with async/await Getting Started with Arrow Functions in JavaScript An Interesting Explanation of async/await in JavaScript Front-end Architecture: Stable and Volatile Dependencies Is it Safe to Compare JavaScript Strings? How to Access Object's Keys, Values, and Entries in JavaScript What Actually is a String in JavaScript? 3 Ways to Shallow Clone Objects in JavaScript (w/ bonuses) Checking if an Array Contains a Value in JavaScript JavaScript Event Delegation: A Beginner's Guide How to Parse URL in JavaScript: hostname, pathname, query, hash 3 Ways to Detect an Array in JavaScript How to Get the Screen, Window, and Web Page Sizes in JavaScript 3 Ways to Check If an Object Has a Property/Key in JavaScript How to Compare Objects in JavaScript Object.is() vs Strict Equality Operator in JavaScript Own and Inherited Properties in JavaScript 5 Differences Between Arrow and Regular Functions How to Use Object Destructuring in JavaScript Your Guide to React.useCallback() 5 JavaScript Scope Gotchas
Solving a Mystery Behavior of parseInt() in JavaScript
Dmitri Pavlutin · 2021-04-20 · via Dmitri Pavlutin Blog

parseInt() is a built-in JavaScript function that parses integers from numerical strings. For example, let's parse the integer from the numeric string '100':


const number = parseInt('100');

number; // 100


As expected, '100' is parsed to integer 100.

parseInt(numericalString, radix) also accepts a second argument: the radix at which the numerical string argument is. The radix argument allows you to parse integers from different numerical bases, the most common being 2, 8, 10, and 16.

Let's use parseInt() to parse a numerical string in base 2:


const number = parseInt('100', 2);

number; // 4


parseInt('100', 2) parses '100' as an integer in numerical base 2: thus it returns the value 4 (in decimal).

That's pretty much a short introduction to parseInt().

1. A mystery behavior of parseInt()

parseInt(numericalString) always converts its first argument to a string (if it's not a string), then parses that numeric string to the integer value.

That's why you can (but should't!) use parseInt() to extract the integer part of float numbers:


parseInt(0.5); // => 0

parseInt(0.05); // => 0

parseInt(0.005); // => 0

parseInt(0.0005); // => 0

parseInt(0.00005); // => 0

parseInt(0.000005); // => 0


Open the demo.

Extracting the integer part of floats like 0.5, 0.05, etc. results in 0. This works as expected.

What about extracting the integer part of 0.0000005?


parseInt(0.0000005); // => 5


Open the demo.

parseInt() parses the float 0.0000005 to... 5. Interesting and kind of unexpected...

Why does parseInt(0.0000005) have such a mystery behavior?

2. Solving the mystery of parseInt()

Let's look again at what parseInt(numericalString) does with its first argument: if it's not a string, then it is converted to a string, then parsed, and the parsed integer returned.

That might be the first clue.

Let's try then to convert manually the floats to a string represenation:


String(0.5); // => '0.5'

String(0.05); // => '0.05'

String(0.005); // => '0.005'

String(0.0005); // => '0.0005'

String(0.00005); // => '0.00005'

String(0.000005); // => '0.000005'

String(0.0000005); // => '5e-7'


Open the demo.

The explicit conversion to a string of String(0.0000005) behaves differently than other floats: it's a string representation of the exponential notation!

That's the second — and a significant clue!

And when the expontential notiation is parsed to an integer, you get the number 5:


parseInt(0.0000005); // => 5

// same as

parseInt(5e-7); // => 5

// same as

parseInt('5e-7'); // => 5


Open the demo.

parseInt('5e-7') takes into consideration the first digit '5', but skips 'e-7'.

Mystery solved! Because parseInt() always converts its first argument to a string, the floats smaller than 10-6 are written in an exponential notation. Then parseInt() extracts the integer from the exponential notation of the float.

On a side note, to safely extract the integer part of a float number I recommend Math.floor() function:


Math.floor(0.5); // => 0

Math.floor(0.05); // => 0

Math.floor(0.005); // => 0

Math.floor(0.0005); // => 0

Math.floor(0.00005); // => 0

Math.floor(0.000005); // => 0

Math.floor(0.0000005); // => 0


Open the demo.

3. Conclusion

parseInt() is the function that parses numerical strings to integers.

Care must be taken when trying to extract the integer part of floats using parseInt().

Floats smaller than 10-6 (e.g. 0.0000005 which is same as 5*10-7) conversed to a string are written in the exponential notation (e.g. 5e-7 is the exponential notation of 0.0000005). That's why using such small floats with parseInt() leads to unexpected results: only the significat part (e.g. 5 of 5e-7) of the exponential notiation is parsed.

Side challenge: can you explain why parseInt(999999999999999999999) equals 1? Write your considerations in a comment below!