What's new

Web JavaScript - h2d and d2h conversion

  • Thread starter stepto
  • Start date
  • Views 654
stepto

stepto

Enthusiast
Messages
249
Reaction score
72
Just wanted to share with you my script that converts a user's decimal value to hexadecimal value, and vice-versa.

I'm happily open to any criticism. :smile:

Code:
        function hexToDec(){
               
                    var hex = prompt ( "Please enter a hexadecimal value to be converted: ", "0" );
                   
                    var dec = parseInt ( hex, 16 );
                   
                    document.writeln ( "Your converted hexadecimal value is: " );
                    document.writeln ( dec );
            }
     
        function decToHex(){
             
                    var dec = prompt ( "Please enter a decimal number to be converted: ", "0" );
                 
                    var hex = ( parseInt( dec, 10 )).toString(16).toUpperCase();
                 
                    document.writeln ( "Your converted decimal number is: " );
                    document.writeln ( hex );
            }
 
        var userChoice = prompt ( "Please enter [1] for hexadecimal to decimal conversion\nPlease enter [2] for decimal to hexadecimal conversion. ", "0" );
     
        while ( userChoice != '1' && userChoice != '2' ){
            alert ( "Please enter a valid choice.");
            var userChoice = prompt ( "Please enter [1] for hexadecimal to decimal conversion\nPlease enter [2] for decimal to hexadecimal conversion. ", "0" );
        }
     
        if ( userChoice == 1 ){ 
            hexToDec();
        }else if( userChoice == 2 ){
            decToHex();
        }
 
Last edited:
Top Bottom