To convert a floating-point number to a whole number in JavaScript, you can use several methods depending on whether you want to round, truncate, or floor/ceil the value. Here’s a breakdown of common approaches:
1. Truncate Decimals (Remove Fraction)
Math.trunc()
Removes the decimal part, leaving the integer (works for positive and negative numbers):
Math.trunc(3.7); // 3
Math.trunc(-3.7); // -3
Bitwise Operators
Truncates by converting to a 32-bit integer (fast but limited to 32-bit range):
3.7 | 0; // 3
-3.7 | 0; // -3
~~3.7; // 3 (double bitwise NOT)
2. Round to Nearest Integer
Math.round()
Rounds to the nearest whole number:
Math.round(3.2); // 3
Math.round(3.5); // 4 (midpoint rounds up)
Math.round(-3.7); // -4
3. Round Down (Math.floor
) or Up (Math.ceil
)
Math.floor()
Rounds down to the nearest integer:
Math.floor(3.7); // 3
Math.floor(-3.7); // -4
Math.ceil()
Rounds up to the nearest integer:
Math.ceil(3.2); // 4
Math.ceil(-3.7); // -3
4. Parse as Integer
parseInt()
Truncates decimals (works for strings and numbers):
parseInt(3.7); // 3
parseInt("4.9"); // 4 (works with strings)
5. Using toFixed(0)
(String Conversion)
Converts to a string and back to a number (rounds to nearest integer):
parseFloat((3.7).toFixed(0)); // 4
parseFloat((-3.7).toFixed(0)); // -4
Key Differences
Method | 3.7 | -3.7 | 3.2 | 3.5 | Notes |
---|---|---|---|---|---|
Math.trunc() | 3 | -3 | 3 | 3 | Removes decimals. |
Math.round() | 4 | -4 | 3 | 4 | Rounds to nearest integer. |
Math.floor() | 3 | -4 | 3 | 3 | Rounds down. |
Math.ceil() | 4 | -3 | 4 | 4 | Rounds up. |
~~num or | 0 | 3 | -3 | 3 | 3 | Truncates (32-bit limit). |
parseInt(num) | 3 | -3 | 3 | 3 | Truncates decimals. |
When to Use Which
- Truncate: Use
Math.trunc()
or bitwise operators (~~
or| 0
). - Round: Use
Math.round()
,Math.floor()
, orMath.ceil()
based on direction. - Edge Cases: Bitwise operators (
~~
,| 0
) fail for numbers outside 32-bit range (e.g.,2147483648.5
→-2147483648
). - String Handling: Use
parseInt()
if working with string inputs.
Example Workflow
const floatNum = 4.9;
// Truncate to integer
const truncated = Math.trunc(floatNum); // 4
// Round to nearest integer
const rounded = Math.round(floatNum); // 5
// Parse as integer (truncate)
const parsed = parseInt(floatNum); // 4
// Bitwise truncation
const bitwiseTrunc = floatNum | 0; // 4
Choose the method that best matches your use case!