How can I perform `integer division javascript` to get the result as an integer, not a float?

For example, when I do:

var x = 455 / 10;

The result is 45.5, but I want x to be 45 (integer division). Is there a built-in way in JavaScript to perform this kind of operation, or should I manually remove the decimal part?

Try using the Math.floor() (Round down) It is the most straightforward and widely used method to get the integer part of the division.

var x = Math.floor(455 / 10);
console.log(x); // Outputs: 45

Math.floor() rounds the result down to the nearest integer, discarding the decimal portion. This is the most common way to perform integer division.

In JavaScript, you can use the bitwise OR (|) operator as a quick trick to floor a number to the nearest integer.

var x = (455 / 10) | 0;
console.log(x); // Outputs: 45

The | 0 operation converts the result to a 32-bit integer, effectively discarding the decimal part. This works because JavaScript automatically converts numbers to integers when using bitwise operators.

If you want to explicitly cast the result into an integer, you can use parseInt().

var x = parseInt(455 / 10);
console.log(x); // Outputs: 45

parseInt() parses the number and returns the integer part by discarding the decimals. However, it’s less efficient compared to Math.floor() and | 0, and it’s usually better to use one of those methods unless you specifically need to parse the result as a string.