How to Convert a Float Number to Whole Number in JavaScript

Converting a floating point number to an integer can be a common requirement in JavaScript programming.

The conversion process involves removing the decimal portion of the number and converting it to a whole number.

There are several ways to do this, and in this tutorial, we will explore the most common methods.


Math.floor()

The Math.floor() function is the most straightforward way to convert a floating-point number to an integer.

The function takes a number as an argument and returns the largest integer less than or equal to the number.

In other words, it rounds the number down to the nearest integer. Here’s an example:

let floatNum = 5.7;
let wholeNum = Math.floor(floatNum);
console.log(wholeNum); // Output: 5

In the above example, floatNum is the floating-point number we want to convert, and Math.floor(floatNum) returns the largest integer less than or equal to floatNum, which is 5.

The result is stored in the wholeNum variable and logged to the console.

Bitwise OR (|)

Another way to convert a floating-point number to an integer is to use a bitwise operator, specifically the bitwise OR (|) operator.

The operator converts the number to a 32-bit integer. Here’s an example:

let floatNum = 5.7;
let wholeNum = floatNum | 0;
console.log(wholeNum); // Output: 5

In the above example, floatNum is the floating-point number we want to convert.

The expression floatNum | 0 converts floatNum to a 32-bit integer and returns the result, which is 5.

The result is stored in the wholeNum variable and logged to the console.

parseInt()

The parseInt() function is another way to convert a floating-point number to an integer.

The function takes two arguments: the number to be converted and the base to use for the conversion.

In most cases, the base is set to 10, which represents the decimal system.

Here’s an example:

let floatNum = 5.7;
let wholeNum = parseInt(floatNum, 10);
console.log(wholeNum); // Output: 5

In the above example, floatNum is the floating-point number we want to convert.

The expression parseInt(floatNum, 10) converts floatNum to an integer using the decimal system and returns the result, which is 5.

The result is stored in the wholeNum variable and logged to the console.


Conclusion

In conclusion, converting a floating-point number to an integer is a simple process in JavaScript.

You can use the Math.floor() function, the bitwise OR (|) operator, or the parseInt() function to achieve the desired result.

Choose the method that best suits your needs, and you’ll be able to convert floating-point numbers to integers in no time!