2

I am trying to solve this problem but i can't. Would need some help. Thank you.

Write a JavaScript code in a Web page dec2hex.html that enters a positive integer number num and converts and converts it to a hexadecimal form. The input should be entered as JavaScript prompt window. The output should be shown as browser popup window (alert).

My code:

<!DOCTYPE html>
<html>
<head>
    <title>Decimal</title>
</head>
<body>
    <script type="text/javascript">
         var decimal = prompt("Write your decimal number");
         var hex = decimal.toString(16);
         alert(hex);
    </script>

</body>
</html>

Examples:

Input: 254

Output: FE

Input: 6779

Output: 1A7B

Sovak
  • 373
  • 1
  • 5
  • 17
  • http://stackoverflow.com/questions/57803/how-to-convert-decimal-to-hex-in-javascript – yas Jun 10 '15 at 12:10

4 Answers4

3

You actually need to parse the prompt in integer :

var decimal = parseInt(prompt("Write your decimal number"));

var hex = decimal.toString(16);
alert(hex);

https://jsfiddle.net/rvzayaph/6/

AshBringer
  • 2,614
  • 2
  • 20
  • 42
1

you can do it like this:

var decimal = prompt("Write your decimal number");
var hex = parseInt(decimal, 16);
Özgür Ersil
  • 6,909
  • 3
  • 19
  • 29
  • This does not work. I just tried it and it didn't give me the hex code of the number i input. – Sovak Jun 10 '15 at 12:15
0

Use this conversion for number to hex

hexString = decimal.toString(16);

and reverse is

decimal = parseInt(hexString, 16);

Rita Chavda
  • 191
  • 2
  • 16
  • Well hexString = decimal.toString(16) is the same is my code and it's not wroking. When i alert(hexString); it prints the same number as the inputed from prompt and not the hex number of the inputed number. – Sovak Jun 10 '15 at 12:31
0

Replace hex = decimal.toString(16) to hex = parseInt(decimal, 16)


To test this in console, use the below:
dec = prompt("Decimal Number");
hex = parseInt(dec, 16);

console.log("DEC: " + dec);
console.log("HEX: " + hex);