使用JavaScript将整数转换为十进制

问题描述 投票:0回答:1

我有一个程序需要将整数转换为二进制和十进制。我有二进制部分工作,但我卡在小数部分。我正在尝试使用intToFloat但不确定这是否正确。这是转换函数的代码。

if (cT[0].checked) {
    // to binary
    var dval = parseInt(val);
    if (isNaN(dval)) {
        alert("input value is not a number");
    }
    else if ((val % 1) !== 0 ) {
        alert("number is not a integer");
    }
    else if (dval < 0) {
        alert("Input value must be a positive integer");
    }
    else {
        convertByArray(dval);
    }
}
else if (cT[1].checked) {
    //to decimal
    var dval = parseFloat(val);
    if (isNaN(dval)) {
        alert("input value is not a number");
    }
    else if ((val % 1) !== 0 ) {
        alert("number is not a integer");
    }
    else if (dval < 0) {
        alert("Input value must be a positive integer");
    }
    else {
        intToFloat(dval);
    }
}
else {
    alert("Please select a conversion type.");
}
}
function convertByArray(dval) {
    var rA = new Array();
    var r,i,j;

    i=0;
    while (dval > 0) {
        r = dval % 2;
        rA[i] = r;
        var nV = (dval - r) / 2;
        $("txtCalc").value = $("txtCalc").value + " Decimal " + dval + " divided by 2 = "
       + nV + " w/Remainder of: " + r + "\n";
       i += 1;
       dval = nV;
}

for(j=rA.length-1; j>= 0; j--) {
       $("txtOut").value = $("txtOut").value + rA[j];
}

}
function intToFloat(num, decPlaces) { 
   return num + '.' + Array(decPlaces + 1).join('0'); 
}

我需要它来显示一个转换为十进制的整数的输出并显示该值,就像它转换为二进制时已经做的那样。

javascript
1个回答
0
投票
parseInt(value, fromBase).toString(toBase)

将其转换为二进制

parseInt(25,10).toString(2) //<== '25' is the value, 10 is the current base. 2 is the base you want to converted. 

将其转换为十进制

parseInt(100011,2).toString(10) 

将其转换为浮动

   var num = 203
    num.toFixed(6)  // asnwer will be 203.000000
© www.soinside.com 2019 - 2024. All rights reserved.