Double Tilde Operator in JavaScript (~~)
In JavaScript, the ~~ operator is a type coercion operator that removes everything after the decimal point of a number. This differs from the ~ operator, which is a bitwise NOT operator that inverts the bits of a value.
Operation
The operator works by first converting its operand to a signed 32-bit integer. This means that even if the operand is a floating-point number or a string, it will be treated as an integer internally. The operator effectively performs the following:
Usefulness
While the ~~ operator may seem like a simple replacement for Math.floor or Math.ceil, it has some limitations:
Therefore, it is generally recommended to use x (unary plus) or Number(x) for type coercion, and Math.floor or Math.ceil for rounding.
Example
Consider the number -43.2:
As you can see, ~~ rounds toward zero while Math.floor rounds down. This behavior can be useful in certain scenarios, such as truncating a number without using a decimal point.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3