Number.prototype.toString(radix) chuyển số sang chuỗi biểu diễn ở cơ số radix (2 đến 36).
Cú pháp
num.toString(radix); // radix: 2-36, mặc định 10
Ví dụ: Số 26
<script>
const num = 26;
document.write('Binary (2): ' + num.toString(2) + '<br>'); // 11010
document.write('Octal (8): ' + num.toString(8) + '<br>'); // 32
document.write('Decimal (10): ' + num.toString(10) + '<br>'); // 26
document.write('Hex (16): ' + num.toString(16) + '<br>'); // 1a
document.write('Base 36: ' + num.toString(36) + '<br>'); // q
</script>
Kết quả
Binary (2): 11010 Octal (8): 32 Decimal (10): 26 Hex (16): 1a Base 36: q
Ví dụ: Số 36
const num = 36;
document.write('Binary: ' + num.toString(2)); // 100100
document.write('Octal: ' + num.toString(8)); // 44
document.write('Decimal: ' + num.toString(10)); // 36
document.write('Hex: ' + num.toString(16)); // 24
Lưu ý
radixphải từ 2 đến 36 — ngoài 범위 throw RangeError.- Số âm: dấu
-được giữ, phần giá trị tuyệt đối chuyển base. - Số thực: chỉ chuyển phần nguyên (trước dấu chấm).
- Dùng cho formatting:
(255).toString(16).padStart(2, '0').toUpperCase()→ "FF".
Ngược lại: Parse string base-N thành số
parseInt('11010', 2); // 26
parseInt('1a', 16); // 26
parseInt('q', 36); // 26
// Hoặc Number() với prefix
Number('0b11010'); // 26 (binary literal)
Number('0x1a'); // 26 (hex literal)
Number('0o32'); // 26 (octal literal)