Home > Web Front-end > JS Tutorial > body text

JavaScript Exploration: Use parseInt() for numerical conversion

高洛峰
Release: 2016-11-28 14:44:23
Original
1411 people have browsed it

You can get a numeric value from a string using parseInt(), this method accepts another radix argument, which is often omitted, but shouldn't be. There may be problems when the string starts with "0". For example, when entering a form field part of the time, in ECMAScript 3, strings starting with "0" are treated as octal, but this has been done in Changed in ECMAScript 5. To avoid contradictions and unexpected results, always specify radix arguments.

var month = "05",
    year = "09";
month = parseInt(month, 10);
year = parseInt(year, 10);
alert(month);
alert(year);
Copy after login

In this example, if you ignore the base parameter, such as parseInt(year), the returned value will be 0, because "09" is treated as octal (such as executing parseInt(year, 8)), and 09 is in It is not a valid number in base 8.

Replacement methods convert strings to numbers, including:

+"08" // 结果是 8
Number("08") // 8
Copy after login

These are usually faster than parseInt() because the parseInt() method, as the name implies, does not simply parse and convert. However, if you want to enter, for example, "08 hello", parseInt() will return a number, and otherwise end up with NaN.

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!