Web JavaScript - h2d and d2h conversion

Discussion in 'Source Code & Tutorial Database' started by stepto, Nov 3, 2015 with 0 replies and 573 views.

  1. stepto

    stepto Enthusiast

    Messages:
    255
    Ratings:
    66
    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: Nov 3, 2015

Share This Page