Maybe this is lame question, if so, I sincerely apologize.
I have encountered on, to me, an interesting challenge.
<button onClick="myFunc()">Click Me</button>
<p id="test"></p>
<script>
function myFunc() {
var n = 15
var a = n.toString(); // outputs 15
var b = n.toString(2); // outputs 1111
var c = n.toString(9); // outputs 16
var d = n.toString(18); // outputs f
var e = n.toString(36); // outputs f
var total = a + "<br>" + b + "<br>" + c + "<br>" + d + "<br>" + e;
document.getElementById('test').innerHTML=total;
}
</script>
I understand 2 will output binary value, and 18 & 36 will output hexadecimal value. But when I put 37 it doesn't output anything.
For example:
var f = n.toString(37);
doesn't output anything.
In the console it says: RangeError: radix must be an integer at least 2 and no greater than 36. Why?
This parameter specifies the base in which the integer is represented in the string. It is an integer between 2 and 36 which is used to specify the base for representing numeric values. Return Value: The num. toString() method returns a string representing the specified number object.
toString(16) converts a number to a hexidecimal value.
toString . For user-defined Function objects, the toString method returns a string containing the source text segment which was used to define the function. JavaScript calls the toString method automatically when a Function is to be represented as a text value, e.g. when a function is concatenated with a string.
radix. An optional argument that specifies the radix, or base, between 2 and 36, in which the number should be represented. If omitted, base 10 is used. Note, however, that the ECMAScript specification allows an implementation to return any value if this argument is specified as any value other than 10.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Bad_radix
Why is it limited to 36? A radix that is larger than 10 uses alphabetical characters as digits. Therefore, the radix can not be larger than 36 as the Latin alphabet has 26 characters only.
what's more, with radix 18 you don't get hexadecimal values. hexadecimal is base 16
As the link in the other answer says, this is because with base 36 there are digits from 0 to z. For bases grater than 36, a few other non alphanumeric symbols should be added as digits.
Anyway, as you can see, base 36 is enough to invoke most of js methods
let bar = {baz(){alert(":)")}};
eval(14643.314021776406.toString(36))()
the code above will alert a smile!
It's a joke, of course :D
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With