Have you ever used parseInt to truncate a number in JavaScript? I used to do it too. But today, I want to show you why that habit might be hurting your code - and how to do it better.
๐ง The Problem
parseInt was designed to convert strings to integers, not to truncate numbers. When you write:
parseInt(4.9); // 4 Does it work? Yes.
Is it clear? Not really.
Is it fast? Definitely not.
โก๏ธ The Better Way
If you're working with a number and want to remove the decimal part, use:
Math.trunc(4.9); // 4 It's faster, clearer, and semantically correct. It also works with negative numbers:
Math.trunc(-4.9); // -4 ๐งช Performance Matters
In simple benchmarks, Math.trunc can be up to 5x faster than parseInt. That matters - especially in loops, animations, or real-time calculations.
๐งจ Other Ways to Truncate Numbers in JavaScript (Use with Caution)
Sometimes you want to truncate a number without using Math.trunc(). Here are some alternatives - each with its own quirks.
๐ธ Bitwise OR (| 0)
This is a clever trick to truncate decimals using bitwise operations.
4.9 | 0; // 4 ~~4.9; // 4 โ
Fast
โ ๏ธ Only works reliably for 32-bit integers. Avoid with large or precise numbers.
๐ธ Double Bitwise NOT (~~)
Similar to | 0, but slightly more readable for some developers.
~~4.9; // 4 ~~-4.9; // -4 โ
Fast
โ ๏ธ Same limitations as | 0.
๐ธ Math.floor() and Math.ceil()
These are rounding functions, not true truncation - but they can be useful depending on the sign of the number.
Math.floor(4.9); // 4 Math.floor(-4.9); // -5 Math.ceil(4.9); // 5 Math.ceil(-4.9); // -4 โ
Clear intent
โ ๏ธ Not truncation - they round up/down.
๐ธ Number.toFixed(0)
This method returns a string, not a number, and it rounds the value.
(4.9).toFixed(0); // "5" Number((4.9).toFixed(0)); // 5 โ
Useful for formatting
โ ๏ธ Not truncation, and returns a string unless converted.
๐ Recommendation
| Method | Truncates? | Returns | Performance | Notes |
|---|---|---|---|---|
Math.trunc() | โ | Number | ๐ผ High | Best choice for clarity and safety |
parseInt() | โ | Number | ๐ฝ Low | Avoid for truncating numbers |
Math.floor() | โ | Number | ๐ผ High | Rounds down, not truncates |
Math.ceil() | โ | Number | ๐ผ High | Rounds up, not truncates |
toFixed(0) | โ | String | ๐ฝ Medium | Rounds and returns string unless converted |
โ Why Best Practices Matter
As a developer, you're not just writing for machines - you're writing for other humans, including your future self. Choosing the right tool makes your code:
- Easier to read
- Faster to run
- More meaningful
๐ฌ Final Thoughts
If you're truncating numbers with parseInt, stop now. Use Math.trunc and write code that makes sense. Small choices lead to better habits - and better software.
Enjoyed this tip? Share it with a friend who's still stuck in parseInt land. Let's do the basics right - then we can do the magic. ๐
Top comments (2)
Very nice
I am glad hear this