How javascript converts decimals to integers
This article mainly shows you "javascript how to convert decimals 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 "javascript how to convert decimals to integers" this article.
JS decimal to integer methods: 1, the use of "parseInt (decimal value)" statement; 2, the use of "~ ~ decimal value" statement; 3, the use of "Math.floor (decimal value)" statement; 4, the use of "Math.ceil (decimal value)" statement; 5, the use of "Math.round (decimal value)" statement.
The operating environment of this tutorial: windows7 system, javascript1.8.5 version, Dell G3 computer.
Method 1: use parseInt ()
The parseInt () function parses a string and returns an integer.
When the value of the parameter radix is 0, or when it is not set, parseInt () determines the cardinality of the number based on string.
When the parameter radix is omitted, the cardinality of the default number for JavaScript is as follows:
If string starts with "0x", parseInt () parses the rest of the string into hexadecimal integers.
If string starts with 0, ECMAScript v3 allows an implementation of parseInt () to parse subsequent characters into octal or hexadecimal numbers.
If string starts with a number from 1 to 9, parseInt () parses it to a decimal integer.
Example: use parseInt () to parse different strings
[xss_clean] (parseInt ("10") + "
"); [xss_clean] (parseInt (" 10.33 ") +"
"); [xss_clean] (parseInt (" 34 45 66 ") +"
"); [xss_clean] (parseInt (" 60 ") +"
"); [xss_clean] (parseInt (" 40 years ") +"
"); [xss_clean] (parseInt (" He was 40 ") +"
); [xss_clean] ("
[xss_clean] (parseInt ("10", 10) + "
"); [xss_clean] (parseInt (" 010 ") +"
[xss_clean] (parseInt ("10", 8) + "
"); [xss_clean] (parseInt (" 0x10 ") +"
[xss_clean] (parseInt ("10", 16) + "
")
Output result:
1010346040NaN101081616
Method 2: take the reverse twice
Var decimal=4;var integer = ~ decimal; / / 4 = ~ ~ 4.123console.log (integer)
Output result:
four
Method 3:Math.floor () rounding down
Math.floor (): returns the largest integer that is less than the parameter value.
Console.log (Math.floor (2.5)); / / 2console.log (Math.floor (- 2.5)); / /-3
Method 4:Math.ceil () rounding up
Math.ceil (): returns the smallest integer greater than the parameter value.
Console.log (Math.ceil (2.5)); / / 3console.log (Math.ceil (- 2.5)); / /-2
Method 5:Math.round () is rounded
Math.round (): rounded.
Console.log (Math.round (2. 5)); / / 3console.log (Math.round (- 2. 5)); / /-2console.log (Math.round (- 2. 6)); / /-3 is all the contents of the article "how javascript converts decimals 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!