Home > Web Front-end > JS Tutorial > Using JavaScript for base conversion to convert string to decimal_javascript tips

Using JavaScript for base conversion to convert string to decimal_javascript tips

WBOY
Release: 2016-05-16 16:35:56
Original
1273 people have browsed it

JS is a very magical language, with many built-in functions that can help us convert numbers (base);

Hexadecimal can be used directly in JS;
var a = 0xff; //255

Convert any base string to decimal, such as binary, octal, hexadecimal. The most commonly used conversion is to integer decimal without writing the second digit;

Copy code The code is as follows:

parseInt("11", 2); // 3 binary to decimal
parseInt("77", 8); // Convert 63 from octal to decimal
parseInt("af", 16); //175 hexadecimal to decimal

Convert decimal to binary, octal, hexadecimal string
Object.toString(n): (n) represents the base, such as

Copy code The code is as follows:

(152).toString(2) // "10011000" ; First use brackets to "package" 152 into an object, or write it as follows;
152..toString(2) // The first point here converts 152 into a float type decimal, and the second point is to introduce the object method;
152..toString(16) // "98" : Convert decimal to hexadecimal
152..toString(32) // "4o": convert decimal to 32

Similarly, the maximum base supported by Javascript is 36 (26 English letters and 10 numbers)

35..toString(36) // "z" : supports the maximum encoding "Z", not case sensitive

If it needs to be completed during the conversion process. You can use the following methods:

Copy code The code is as follows:

/**
* @param num The 16 numbers that need to be completed
* @param len The number of digits to be filled in. This is
* @returns completed string
**/
function format(num, len) {
var l = num.length;
if (num.length < len) {
for (var i = 0; i < len - l; i ) {
num = "0" num;
}
}
return num;
}
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