Java also has the Integer. parseInt () method, but the parseInt Processing Method of JavaScript is not the same as that of Java and other strong Integer languages. Therefore, some people often get an exception because of improper use of this method.
The following is a Java code used to convert a string 020 to an integer.
Copy codeThe Code is as follows:
Public class Test {
Public static void main (String args []) throws Exception {
String str = "020 ";
System. out. println (Integer. parseInt (str ));
}
}
The output result is 20.
The following is a piece of JavaScript code that converts the string 020 to an integer.
Copy codeThe Code is as follows:
Var str = "020 ";
Var num = parseInt (str );
Alert (num );
The output result is 16.
Why?
Whether Java or JavaScript, The parseInt method has two parameters. The first parameter is the object to be converted, and the second parameter is the base number of the system, which can be 2, 8, 10, 16, it is processed in decimal format by default. however, in JavaScript, numbers starting with 0 are considered to be processed in octal mode, while 0x numbers are considered to be processed in hexadecimal mode. therefore, the calculation of the above JavaScript code is incorrect.
Is the impact big?
Big! Great! This is often used to calculate the price. Once the price is incorrect, it is misleading for users, and a good website should not mislead users. in the DEMO below, the hexadecimal format is not specified. you can enter a number starting with 0 in the number box. Click the calculation button and the calculated value is much smaller than or equal to the expected value (for example: there is no such value as 019 in octal, so the value is 1, 9 is ignored ).
There is no DEMO specified for the parseInt function.
How to modify it?
As mentioned above, there are two parameters. The second parameter can specify the hexadecimal format used for calculation.
Copy codeThe Code is as follows:
ParseInt (num, radix );
So we can rewrite the problematic JavaScript code into the following code.
Copy codeThe Code is as follows:
Var str = "020 ";
Var num = parseInt (str, 10 );
Alert (num );
In this case, we will rewrite some previous demos as follows:
Specifies the DEMO with the hexadecimal value of 10 for the parseInt function.
Remember, when using the parseInt Method on JavaScript, the above-mentioned parameters must be included.