Home >Web Front-end >JS Tutorial >Using JavaScript's parseInt for rounding_javascript skills

Using JavaScript's parseInt for rounding_javascript skills

WBOY
WBOYOriginal
2016-05-16 18:06:451215browse

Java also has the Integer.parseInt() method, but the way JavaScript handles parseInt is different from that of Java and other strong integer languages, so people often get exception returns due to improper use of this method.

The following is a paragraph Java code, used to convert string 020 to integer.

Copy code The 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, which also converts the string 020 into an integer.
Copy code The code is as follows:

var str = "020";
var num = parseInt(str);
alert(num);

The output result is 16

Why?
Whether it is Java or JavaScript, the parseInt method has two parameters, the first parameter It is the object to be converted. The second parameter is the base, which can be 2, 8, 10, 16. The default is decimal. But in JavaScript, numbers starting with 0 are considered to be processed in octal, 0x The number is considered to be processed in hexadecimal. So the above JavaScript code calculation is wrong.

Is it a big impact?
Big! Big! Because this is often used to calculate prices, once the price is wrong , for users, this is misleading, and a good website should not mislead users in this way. In the DEMO below, there is no system specified. You can enter a number starting with 0 in the quantity box, and click Calculate button, the calculated value will be smaller than expected, or much smaller (for example: there is no value like 019 in octal, so the value becomes 1, and 9 is ignored).
How to modify the DEMO

that does not specify a base for the parseInt function?
As mentioned before, there are two parameters, and the second parameter can specify the base used for calculation.

Copy code The code is as follows:

parseInt(num, radix);

So we can rewrite the problematic JavaScript code into the following code.
Copy the code The code is as follows:

var str = "020";
var num = parseInt(str, 10);
alert(num);

If we handle it this way, we Rewrite some of the previous DEMO, as follows:
Specify the DEMO with base 10 for the parseInt function
Remember, when using the parseInt method on JavaScript, you must bring the base parameter.
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn