Explain Codes LogoExplain Codes Logo

How do I convert a float number to a whole number in JavaScript?

javascript
math-functions
number-conversion
javascript-performance
Nikita BarsukovbyNikita Barsukov·Sep 10, 2024
TLDR

To convert a float to a whole number in JavaScript consider these options:

let num = 3.56; Math.round(num); // 4, closest integer Math.floor(num); // 3, rounds down Math.ceil(num); // 4, rounds up Math.trunc(num); // 3, ignores the decimal part

For power users, here's the bitwise way:

let truncated = ~~num; // 3, oops, decimals got lost let bitwised = num | 0; // 3, casually ignores the decimals

Variety of scenarios

Dealing with negatives

Handling negative floats? Use Math.ceil() to round up toward zero:

let negativeNum = -3.56; Math.ceil(negativeNum); // -3, as it sneakily crawls towards zero

Beware! Math.floor() shifts negative floats away from zero.

Parsing party

When you want to parse a float into an integer without any rounding shenanigans:

parseInt(num, 10); // 3, "I respect your decimal dignity, but I only need the integers."

Great with strings that represent floats. Remember to control the radix for a steady parse feast!

Big numbers, big worries

Bitwise operations (~~, | 0), are speed demons but struggle with numbers beyond 32-bit integer range:

let bigNum = 2147483648.456; let truncatedBigNum = bigNum | 0; // Uh-oh! Precision alarm

For the big ones stick to the safer Math.trunc() or good old basic arithmetic (value - value % 1).

Precision points and large integers

Precision priorities

For high-precision tasks, avoid bitwise operations and pick Math.round(), Math.trunc(), or parseFloat() wisely:

let accountBalance = 100.9999; Math.trunc(accountBalance); // 100, "Sorry, no rounding up on your balance"

Jumbo integers

For massive integer values beyond the safe 32-bit range, steer clear of bitwise operations. Stick to Math.trunc() or "fraction subtraction" (value - value % 1).

Measuring performance

Different methods have separate performance profiles. Use JSPerf tests to find the fastest solution for your case. But cross-check with browser compatibility - not all JavaScript engines behave the same.