ES6 – Convert To Integer

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 -(231) to 231 - 1. If the number is outside of that range it will be converted to a number within that range (eg. -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! 😎

    EcmaScript 6 – String.prototype.repeat()

    One simple function that is on the roster to be released in EcmaScript 6 is String.prototype.repeat. The following can be used to define it in browsers which don’t currently have it defined natively:

    String.prototype.repeat = String.prototype.repeat || function(count) {
        return Array(count >= 0 ? parseInt(count, 10) + 1 : -1).join(this);
    };
    

    Here are some examples of using this function (modified from the originals found on MDN):

    alert("->".repeat(-1));     // RangeError
    alert("->".repeat(0));      // ""
    alert("->".repeat(1));      // "->"
    alert("->".repeat(2));      // "->->"
    alert("->".repeat(3.6));    // "->->->" (count will be converted to integer)
    alert("->".repeat(1/0));    // RangeError
    

    There is more information about this new JavaScript function here.

    EcmaScript 6 – Math.sign()

    One function I didn’t think would be doable in most browsers was the Math.sign. My main worry was that on the MDN page it specifies a difference between negative zero and positive zero. After doing some research I found this page which helped me realize there is a way to determine if you are dealing with normal zero or negative zero. With that in mind, my proposed definition for Math.sign is as follows:

    Math.sign = Math.sign || function(n) {
      return (n = +n) ? n < 0 ? -1 : 1 : n;
    };
    

    As far as I can tell, this JavaScript function definition is a good equivalent to make the function available on browsers that dont yet natively provide this feature. Have fun! 😎