Get the App
SLTechnology News&Howtos  ›  Development  › 

How to convert Float to Integer by js

Shulou Source: shulou.com Published: 2022-06-01 04:58:33 10月19日 Update

This article mainly shows you "js how to achieve Float to Integer", the content is easy to understand, clear, hope to help you solve your doubts, the following let the editor lead you to study and learn "js how to achieve Float to Integer" this article.

Fast Float to Integer

We can usually use Math.floor (), Math.ceil (), and Math.round () to convert float types to integer types.

But there is a faster way 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 positive, then n | 0 is effectively rounded down. If n is negative, it is effectively rounded up. More precisely, the result of this operation is to delete the content after the decimal point directly and truncate the floating point to an integer, which is different from the other methods mentioned above.

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.

Working with scen

Bit or operator can be used to remove any number of numbers from the end of an integer. This means that we don't have to use such code to convert between types.

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

Instead, we can implement our functions in the following ways

Console.log (1553 / 10 | 0) / / Result: 155console.log (1553 / 1000 | 0) / / Result: 15console.log (1553 / 1000 | 0) / / Result: 1 above are all the contents of the article "how to convert Float to Integer in js". 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 content valid points articles types methods positive numbers negative numbers operators Learning help Enforcement Operations Special same reason between Code Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Apple OPPO Reno NVidia macOS vpn