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 (0)