Get the App
SLTechnology News&Howtos  ›  Development  › 

How js converts floating-point numbers to integers

Shulou Source: shulou.com Published: 2022-06-01 03:49:11 10月29日 Update

This article mainly shows you "js how to convert floating-point numbers to integers", the content is easy to understand, clear, hope to help you solve your doubts, the following let Xiaobian lead you to study and learn "js how to convert floating-point numbers to integers" this article.

Convert floating point numbers to integers

You usually use Math.floor (), Math.ceil (), or Math.round () to convert floating-point numbers to integers. There is also a faster way in JavaScript to truncate floating-point numbers to integers using | (bits or operators).

Console.log; > Result: 23console.log (- 23.9 | 0); > Result:-23

| the behavior depends on whether you are dealing with positive or negative numbers, so it is best to use this shortcut only when you are sure.

If n is a positive number, then n | 0 effectively rounds down. If n is negative, it is effectively rounded. More precisely, this operation deletes the contents after the decimal point and truncates the floating point to an integer. You can also use ~ ~ to get the same rounding effect, and as mentioned above, virtually any bit operator forces a floating-point number to be an integer. These special operations are effective because once forced to an integer, the value remains the same.

| it can also be used to delete any number of numbers from the end of an integer. This means that we do not need to convert types like this:

Let str = "1553"; Number (str.substring (0, str.length-1)); > Result:

We can use the | operator instead as follows:

Console.log (1553 / 10 | 0) > Result: 155console.log (1553 / 1000 | 0) > Result: 15console.log (1553 / 1000 | 0) > Result: 1 is all the content of the article "how js converts floating-point numbers to integers". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

Tags: Integers points content valid articles positive numbers negative numbers operators learning help coercion operations normal special same rounded depending on as above as mentioned above Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno OPPO Reno Redmi Huawei MySQL Shulou Information