简体   繁体   中英

Number converter is not converting digits after decimal point

Actually I am a student and I had just started to programme in Javascript. I have created a binary to octal to hexadecimal to decimal converter which is working quite good but the digits after decimal point are not converted please help me as necessary

I can't figure out the problem

My project codes

  <html>
    <head>
        <title> Convertor </title>




</head>
<body>
    <input id="bin" oninput="Convert('bin', 2)" placeholder="bin" spellcheck="false">
<input id="oct" oninput="Convert('oct', 8)" placeholder="oct" spellcheck="false">
<input id="dec" oninput="Convert('dec', 10)" placeholder="dec" spellcheck="false">
<input id="hex" oninput="Convert('hex', 16)" placeholder="hex" spellcheck="false">

    <script>


    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 = "" }
  }
}

    </script>

</body>

Use parseFloat instead of parseInt to parse decimal numbers. You cannot pass the second argument - the radix - when using parseFloat .

Fathyb mentioned that parseFloat has no radix parameter. And there is a simple reason. What du you expect as result when converting 3.5 to binary? 3 equals 0000011 and 5 is 0000101. But 0000011.00000101 is not a valid binary format.

That means as far as i know your code is fine because floats are not supported. ;o)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM