Вопрос

I found this code in a SO answer as a way to truncate a number into an integer in Javascript:

var num = -20.536;
var result = num | 0;
//result = -20

Is this a valid way to truncate a number in Javascript, or it is some kind of hack? Why does it works only with numbers less than 2147483647?

Это было полезно?

Решение

That method works by implicitly converting the number to a 32-bit integer, as binary operators use 32-bit integers in their calculations.

The drawbacks of that method are:

  • The desired operation is hidden as an implicit effect of the operator, so it's not easy to see what the intention of the code is.

  • It can only handle integers within the range of a 32-bit number.

For any regular case you should use the Math.floor or Math.ceil methods instead, it clearly shows what the intention of the code is, and it handles any number within the precision range of a double, i.e. integers up to 52 bits:

var num = 20.536;
var result = Math.floor(num); // 20

var num = -20.536;
var result = Math.ceil(num); // -20

There is no round-towards-zero method in Javascript, so to do that you would need to check the sign before rounding:

var result = num < 0 ? Math.ceil(num) : Math.floor(num);

Другие советы

Use Javascript's parseInt like so:

var num = -20.536;
var num2int = parseInt(num);

return num2int; //returns -20

Tada! num is now an int with the value of -20.

If you use parseInt you can go from -2^53 to +2^53:

parseInt(-20.536) // -20

parseInt(9007199254740992.1234) // 9007199254740992

Why +/- 2^53? This is because JavaScript uses a 64-bit representation for floating point numbers, with a 52-bit mantissa. Hence all integer values up to 2^53 can be represented exactly. Beyond this, whole numbers are approximated.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top