There are various ways to convert a string or a floating point number to an integer in JavaScript, but not all of them may suit your needs. In this post we will examine four different ways and then we will see which is the best in all cases.

### Solution #1: `~~x`

If we are dealing with smaller number then we can leverage bit-wise operators such as bit-wise negation (`~`

). The reason we can only use this solution for smaller numbers is because bit-wise operations can only be executed on a number in the range of `-(2`

to ^{31})`2`

. If the number is outside of that range it will be converted to a number within that range (eg. ^{31} - 1`-2147483649`

becomes `2147483647`

and `2147483648`

becomes `-2147483648`

).

### Solution #2: `parseInt(x, 10)`

There is actually a function that will convert strings into numbers called `parseInt()`

. We can use this function and specify the base to ensure that numbers starting with `0`

will not be parsed as octals (eg. `parseInt('010')`

produces `8`

in older versions of ECMAScript).

### Solution #3: `+parseFloat(x, 10).toFixed(0)`

We can also use the equivalent function to `parseInt()`

for floats which is `parseFloat()`

. After that we can use `Number.prototype.toFixed()`

to make the number a string representation of the truncated number. Finally we can prefix this expression with a plus sign (`+`

) to convert the string to a number again.

### Solution #4: `Math.trunc(x)`

We can use the newer `Math.trunc()`

function which should in theory just do what we want ðŸ˜† .

### Results

Below are the results of using your browser to test out each solution:

### Conclusion

If you have looked through the results above on a modern browser (one implementing `Math.trunc()`

) you’ll notice that for all of our test cases, it is the only solution that works for them all. Therefore, if you are looking to convert floating-point numbers to integers or strings to integers, the most convenient and straightforward way may in fact be ES6’s new `Math.trunc()`

function. Let me know what you think and as always, happy coding! ðŸ˜Ž

## 4 Comments

## mightyplow · June 27, 2017 at 12:00 PM

One can also use Math.floor(‘12345.67’). It doesn’t strip off appending text, but it also converts the string into an integer. Same with Math.ceil and Math.round.

## Ed G · June 27, 2017 at 2:29 PM

According the MDN, you can implement Math.trunc with Math.floor and Math.ceil. This is a polyfill:

Math.trunc = Math.trunc || function(x) {

if (isNaN(x)) {

return NaN;

}

if (x > 0) {

return Math.floor(x);

}

return Math.ceil(x);

};

## Robin Millette · June 28, 2017 at 2:24 AM

Thanks for the post. It got me thinking and here’s one more that I think satisfies most cases (haven’t check for all).

const trunc = (n) => new Int32Array([n])[0]

Good day ðŸ™‚

## Robin Millette · June 28, 2017 at 2:31 AM

Ah, so it suffers from the same fate as ~~

“Doesn’t work for 9999999999: 9999999999 â‰ 1410065407”