Explain Codes LogoExplain Codes Logo

How can I remove the decimal part from JavaScript number?

javascript
prompt-engineering
functions
performance
Anton ShumikhinbyAnton Shumikhin·Dec 11, 2024
TLDR

To surgically remove decimals from a JavaScript number, Math.trunc() is your go-to operation—but it's not the only one:

let number = 123.456; let noDecimals = Math.trunc(number); // 123, "Bye-bye decimals, it's been real (number)."

Truncation, the JavaScript way

Besides Math.trunc(), JavaScript harbors multiple methods to remove decimals. Mind you, each method has unique quirks and use-cases. Here's a brief guide to JavaScript's decimal removal operations:

MethodSpecialtyReturn Type
Math.trunc(number)Direct approach.Number
~~numberThe master of performance.Number
parseInt(number)Returns just the integer part. Can't ask more.Number
Math.floor(number)Rounds down, like your pessimistic friend.Number
Math.round(number)Rounds to nearest. Unbiased, just the way we like it.Number

However, remember, Bitwise operations (~~) do come with a baggage — a 32-bit limit. So, handle large numbers with care!

Rounding concerns and precision

Thanks to the quirks of floating-point arithmetic, a method like Math.round() could give you a surprise party by rounding your number to the next integer! To avoid unexpected surprises, Math.floor() is your friend for negative numbers, and Math.ceil() is a reliable buddy for positive numbers.

Polyfill for Math.trunc()

For those older browsers that didn't get the memo about Math.trunc(), use a polyfill:

if (!Math.trunc) { Math.trunc = function(v) { return v < 0 ? Math.ceil(v) : Math.floor(v); // "Vintage browser? No Problem!" }; }

The string way, if you so desire

If your situation demands a string representation without decimals, try Number.toFixed(0). Be aware though, despite its vagabond lifestyle as a string, it might need to be converted back to a number:

let number = 123.456; let noDecimalsString = number.toFixed(0); // "123", "Just a number having an identity crisis." let noDecimalsNumber = Number(noDecimalsString); // 123 - Back to natural being

Arithmetic with precision

Floating-point arithmetic is a fascinating beast but can come with precision issues. Actions like multiplication by a power of 10 before truncating may betrays you due to these issues. It's always helpful to understand how the machine views numbers and does Math.

Performance considerations

When it's all about performance, Bitwise operators (like ~~) are your speedsters. Consider them for truncation, but remember that high-precision matters—sometimes it's best to roll out with good-ol' Math functions.