Conversion from Decimal to octal, binary and hexadecimal in javascript

前端 未结 5 1469
花落未央
花落未央 2021-02-08 17:23

I have a form where a user enters a decimal number and then from the dropdown menu he chooses if he wants to convert it either to binary, octal or hexadecimal by clicking on a c

5条回答
  •  情书的邮戳
    2021-02-08 17:50

    Here's some great code I just made to convert between binary, octal, decimal and hexadecimal:

    function id(id) {
      return document.getElementById(id);
    }
    function Convert(s, n) {
      if(parseInt(id(s).value, n)) {
        if("bin" != s) { id("bin").value = parseInt(id(s).value, n).toString(2) }
        if("oct" != s) { id("oct").value = parseInt(id(s).value, n).toString(8) }
        if("dec" != s) { id("dec").value = parseInt(id(s).value, n).toString(10) }
        if("hex" != s) { id("hex").value = parseInt(id(s).value, n).toString(16) }
      } else {
        if("bin" != s) { id("bin").value = "" }
        if("oct" != s) { id("oct").value = "" }
        if("dec" != s) { id("dec").value = "" }
        if("hex" != s) { id("hex").value = "" }
      }
    }
    
    
    
    

    Small and simple, perfect for anyone trying to find one of that kind.

提交回复
热议问题