<html>
<head>
<script>
"use strict";
function hexidecimal() {
	var num = document.getElementsByName('number')[0].value;
	var hex = num.toString(16);
alert(hex);
alert(num.toString(2));
}
</script>
</head>
<body>
<form id="form">
<input type="text" name="number" />
<input type="button" value="Hex" onClick="hexidecimal();" />
</form>
</body>
</html>

Above is the current code I have, I expect it to output the contents of whatever is held in the number input box as a hexidecimal number, instead it outputs whatever number is put into the box as base 1. Can anyone shed some light on what I have done wrong please?

Thanks

Dani AI

Generated

The input element returns a string, so calling toString(16) on that string does not perform numeric conversion. In other words, String.prototype.toString ignores any radix argument, so you just get the original text back. As suggested, convert the input to a Number first and then call the Number version of toString to get a hex representation.

Two concise ways to convert and then get hex:

(+num).toString(16)
Number(num).toString(16)

Both coerce the input string to a numeric value and then produce the hex string. If the input can be non-integer or invalid, validate first (trim whitespace, check for empty string, and use isNaN/Number.isFinite to detect bad input). If you want only the integer part, make that explicit (round, floor, or use integer parsing with an explicit radix).

Additional practical notes based on the thread:

  • If you use parseInt, always pass the radix (e.g., base 10) to avoid legacy-octal or other surprises.
  • Watch for leading/trailing whitespace or non-numeric characters in the textbox; these cause Number(...) to return NaN.
  • Consider using input type="number" or client-side validation to limit bad input, and attach handlers with addEventListener instead of inline onClick for cleaner code.

Relevant documentation: String.prototype.toString, Number.prototype.toString, and the note on parseInt and radix.

Recommended Answers

All 2 Replies

Convert your num (string) to an int first, using parseInt:

var hex = parseInt(num).toString(16);

Thanks very much.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.