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

1

4 Answers 4

4

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/

Sign up to request clarification or add additional context in comments.

1 Comment

hex = dec.toString(16); is the same as my code. Doesn't work.
1

you can do it like this:

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

1 Comment

This does not work. I just tried it and it didn't give me the hex code of the number i input.
0

Use this conversion for number to hex

hexString = decimal.toString(16);

and reverse is

decimal = parseInt(hexString, 16);

1 Comment

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.
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);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.