Converts a decimal number into a format similar to 0x000100 or hexadecimal number # 000100
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="utf-8"> 5 <title>Dec to Hex</title> 6 </head> 7 <body onload="doIt()"> 8 <p id="demo1"></p> 9 <p id="demo2"></p> 10 </ Body > . 11 < Script > 12 is function the doIt () { 13 is document.getElementById ( " the demo1 " ) .innerHTML = DEC2HEX ( " 0x " , 256 ); 14 document.getElementById ( " demo2 " ) .innerHTML = DEC2HEX ( " # " , 256 ); 15 } 16 // decimal to 6-digit hexadecimal number . 17 function DEC2HEX (prefix, value) { 18 is var hexCode = value.toString(16); 19 var zeroes = "000000"; 20 var remain = zeroes.length - hexCode.length; 21 return prefix + zeroes.substr(0, remain) + hexCode; 22 } 23 </script> 24 </html>
第 10 行:var hexCode = value.toString(16);
Syntax: NumberObject.toString (radix)
Definition and Usage: toString () method to convert a Number object as a string, and returns the result.
Reference: JavaScript toString () method
第 21 行:return prefix + zeroes.substr(0, remain) + hexCode;
语法:stringObject.substr(start,length)
Definition and Usage: substr () method in the string can be extracted from the start number of the start of the specified character index.
Reference: JavaScript substr () method