This post will discuss how to convert float to nearest integer in JavaScript.

There are several ways to convert a float to the nearest integer in JavaScript, depending on how we want to round the decimal part. Here are some of the most common functions:

1. Using Math object

The Math object provides various mathematical functions that are useful in converting a float to an integer. They can be used by calling them with a number as an argument, like this: Math.function(number).

  • We can use the Math.round() function, which rounds a float to the nearest integer, following the standard mathematical rules.
  • We can use the Math.floor() or Math.ceil() functions to round a float to the nearest integer. The difference is that floor rounds down, while ceil rounds up.
  • We can use the Math.trunc() function, which removes the fractional part of a number and returns the integer part. However, this function is only available in ECMAScript 6 or later.

 
The following code illustrates this:

Download  Run Code

2. Using parseInt() function

The parseInt() function parses a string argument and returns an integer of the specified radix (base). We can use this function to convert a float to an integer by passing it as a string argument and specifying the radix as 10 for decimal numbers. For example, to convert the float 3.14 to an integer, we can use:

Download  Run Code

3. Using bitwise operators

Bitwise operators perform operations on the binary representation of numbers, and can be used to convert a float to an integer by truncating the fractional part. For example, we can use the bitwise OR operator (|) with zero as the second operand to convert a float to an integer. For example, to convert the float 3.14 to an integer, we can use:

Download  Run Code

 
The bitwise operators are fast and concise ways of converting a float to an integer, but they may not work as expected for large numbers or negative numbers.

That’s all about converting float to nearest integer in JavaScript.