javascript convert float to int

How to convert a float to an integer using JavaScript?

Converting a float to an integer in JavaScript is a common task that you may encounter while working with numbers. In this post, we will discuss various ways to convert a float to an integer in JavaScript.

Method 1: Using parseInt()

The parseInt() function in JavaScript can be used to convert a floating-point number to an integer.


let floatNum = 3.14;
let intNum = parseInt(floatNum);
console.log(intNum);

The above code will output:


3

Here, the parseInt() function takes the floatNum variable as input and returns an integer value of 3. Note that if the floatNum variable has a decimal value of .5 or greater, parseInt() will round up to the nearest integer.

Method 2: Using Math.floor()

The Math.floor() function in JavaScript can be used to round down a floating-point number to the nearest integer.


let floatNum = 3.75;
let intNum = Math.floor(floatNum);
console.log(intNum);

The above code will output:


3

Here, the Math.floor() function takes the floatNum variable as input and returns an integer value of 3. Note that Math.floor() always rounds down to the nearest integer.

Method 3: Using Bitwise Operators

Another way to convert a float to an integer is by using bitwise operators. The following code converts a float to an integer using the bitwise OR operator:


let floatNum = 3.14;
let intNum = floatNum | 0;
console.log(intNum);

The above code will output:


3

Here, the bitwise OR operator performs a type conversion on the floatNum variable and returns an integer value of 3.

Method 4: Using Math.trunc()

The Math.trunc() function in JavaScript can be used to remove the decimal part of a floating-point number and return the integer value.


let floatNum = 3.75;
let intNum = Math.trunc(floatNum);
console.log(intNum);

The above code will output:


3

Here, the Math.trunc() function takes the floatNum variable as input and returns an integer value of 3. Note that Math.trunc() always truncates the decimal part of a floating-point number.

Conclusion

In this post, we discussed various ways to convert a float to an integer in JavaScript. You can choose any method depending on your use case and preferences.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe