I am trying to convert a DEC number to HEX using JavaScript.
The number I am trying to convert is 28.
I have tried using:
function h2d(h) {return parseInt(h,16);}
however it returns 40
I have also tried using:
function d2h(d) {return d.toString(16);}
however it returns 28
The final result should return 1C but I can’t seem to work it out.
Does anyone know where I have gone wrong?
It sounds like you’re having trouble because your input is a String when you’re looking for a number. Try changing your d2h() code to look like this and you should be set:
The plus sign (
+) is a shorthand method for forcing a variable to be a Number. Only Number’stoString()method will take a radix, String’s will not. Also, your result will be in lowercase, so you might want to force it to uppercase usingtoUpperCase():So the result will be: